No, if in a shell script?

I tried to do the opposite if in the shell to do something only if the value in the hash does not exist. I learned how 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 find out if myhash [$ key] exists or not here: The easiest way to check the index or key in an array?

I also learned to add! before the expression to make the opposite if clause: How to make an "if not true condition"?

But the following expression

if ! [ ${myhash[$key]+abc} ]; then
     echo $key

fi

does not work, and no information is printed. No error message.

I tried this:

[ ${myhash[$key]+abc} ] && echo $key

And received an error message:

abc: command not found

Can someone tell me how to make it work?

+3
3

-,

[ ${myhash[$key]+abc} ]

, . ${myhash[$key]} , ( ), "abc" . , myhash[$key]="", , . , ! [ ${myhash[$key]+abc} ] .

, "abc" myhash, , , "abc" :

if [[ ${myhash[$key]+abc} == abc ]]; then
    echo "$key does not exist in myhash"
else
    echo "myhash[$key]=${myhash[$key]}"
fi
+2

, , , , .

:

#!/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

: " ?"

, , !.

[ ${myhash[$key]+abc} ] && echo $key, abc: command not found, . .

, , ${myhash[$key]+abc} && echo $key. , , , , .

+1

? , , [ ${array[key]+abc} ].

If so, the command completes successfully, so the command is executed after &&( echo "exists")

You want to check if it exists. Thus, you want your command to be executed if the part [..]fails. So use ||instead &&:

[ ${myhash[$key]+abc} ] || echo "does not exist"

&&: continue with the next command only if the first is successful

||: execute only the following command, if at first it was not possible to execute

0
source

All Articles