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

Time:12-08

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related