0

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?

3
  • 2
    Your myarray is not an array. It is a scalar holding the complete output of your script. Commented Dec 8, 2021 at 7:24
  • @user1934428 correct, I understand, that's why I mentioned array like variable. So what do you think? Commented Dec 8, 2021 at 7:25
  • I would first transform the output of myscript into a more convenient format. You don't need the square brackets or the comma, and most likely you don't need the double quotes either. You have not specified in your post, what the strings in the output can contain. In your example they contain neither spaces nor newlines, but will this always be the case? After this is done, I would a real array to store the data. See this tutorial on how this can be done. Commented Dec 8, 2021 at 7:29

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.