简体   繁体   中英

How to search if a value is present in array like variable using bash script?

I have the below text, as the output of some command myscript.sh ;

[
    "string-1", 
    "string-2"
]

I have stored the output to some variable like below;

myarray=$(myscript.sh)

Now, I would like to echo value not present if the string string-3 is not present in the array, something like the code below;

value="string-3"
if [[ ! " ${myarray[*]} " =~ " ${value} " ]]; then
    echo "value not present"
fi

This code will output value not present even if the value is present. What can be done to fix this issue?

Thanks in advance.

The myarray variable is a string, and regular expressions can be used to determine whether it contains the specified substring.

myarray=([
    "string-1", 
    "string-2"
])
value="string-3"
if [[ ! "$myarray" =~ .*"$value".* ]]; then
    echo "value not present"
fi

Is the input a JSON array? If so, you should use a JSON-aware tool, like jq , to deal with it. Something like this:

if jq -e --arg value "$value" 'any(. == $value)' <<<"$myarray" >/dev/null; then

Explanation: --arg value "$value" copies the shell variable value into a jq variable with the same name. <<<"$myarray" passes the value of that variable as input (since it's not a bash array, the [*] is irrelevant). The filter any(. == $value) returns true if any array elements match $value , false otherwise. The -e option tells jq to use that result as its exit status, and >/dev/null discards the textual output. Since if uses the exit status of the command as its condition, that should be all you need.

Rewrite it like this:

if [[ ! $myarray =~ $value ]]; then
    echo "value not present"
fi

Or like that:

[[ $myarray =~ $value ]] || echo "value not present"

Those "" spoiling everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM