Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there no unless in shell script?

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?

like image 500
olala Avatar asked Oct 27 '25 01:10

olala


1 Answers

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
like image 156
chepner Avatar answered Oct 29 '25 14:10

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!