0

I have an array that contains

line number 1
line number 2
line number 3
line number 4
line number 5

Then I ask for the user input:

read userInput
echo $userInput

And then I try to match the user input, which is a number to my array

for i in "${!array[@]}";do
if [["${array[$i]}"="$userInput"]]
then
    echo "~"
    echo " $i"
fi
done

But this doesn't work. The desire output is this:

4
line number 1
line number 2
line number 3
~line number 4
line number 5

Can anyone help me please?

K.U
  • 25

1 Answers1

1

The conditional [[ .. ]] needs whitespace around the operators and values, i.e.

[[ "${array[$i]}" = "$userInput" ]]
  instead of 
[["${array[$i]}"="$userInput"]]

(The latter is interpreted as one word, and the shell tries to find a command with that name.)

Also, ${!array[@]} gives you the indexes to the array. I'm not sure if that's what you want, since in the script you print out the index with echo $i, but your sample output seems to contain the string stored in the array. If don't need the indices in particular, you can just use for value in "${array[@]}".

Then, if you want to match a partial pattern, you need to explicitly tell the shell that anything before and after the pattern should be accepted: [[ "$var" = *$pattern* ]] (no quotes around the pattern). (See here)

So, paraphrasing a bit:

A=("abc" "def" "ghi")
pat=e
for val in "${A[@]}"; do 
    [[ "$val" = *$pat* ]] && echo -n "~"
    echo "$val"
done

prints

abc
~def
ghi
ilkkachu
  • 138,973
  • I tried this and I got pat: command not found – K.U Oct 12 '16 at 21:20
  • nevermind I got it to work :) Thanks a ton – K.U Oct 12 '16 at 21:21
  • ${array[$i]} is the result of trying different thing with my code, initially I also use ${array[@]} – K.U Oct 12 '16 at 21:22
  • @K.U, did you perhaps put spaces around the assignment? As in pat = something? They don't belong there. Anyways, of course you can set the variable with read, I just used a straight assignment to simplify the example. Note that "${array[@]}" needs quotes around it to be useful, without them you get word-splitting. – ilkkachu Oct 12 '16 at 21:24