1

I am trying to declare an array in my shell script and then have written a for loop to access those array elements into another file. But it is only taking the first element. I've tried the below :

raw_cd=(1150 1151)
i=0


for i in "${raw_cd[@]}"
do
  grep -wr  "${raw_cd[@]}" file1.txt  > /opt/tmp/raw.txt
  echo "$i"
done

It is taking only the first element 1150 and also giving output as :-

file1.txt:|1150|
file1.txt:|1150|
file1.txt:|1150|

where am i doing wrong?

6
  • It seems you haven't increased i or remove i=0 completely Commented Mar 3, 2021 at 9:26
  • don't you mean grep -wr "$i" file1.txt instead? Commented Mar 3, 2021 at 9:26
  • @Amadan but $i would give me the index count, is'nt? Commented Mar 3, 2021 at 9:33
  • @Hellious how and where in the code can i do that? Commented Mar 3, 2021 at 9:34
  • 1
    > /opt/tmp/raw.txt overwrites the file each loop. Did you mean to >> /opt/tmp/raw.txt? Commented Mar 3, 2021 at 10:24

1 Answer 1

2

for does not deal with indices, just raw values. Thus,

raw_cd=(1150 1151)
for i in "${raw_cd[@]}"
do
  echo "$i"
done

will print

1150
1151

If you want to use indices, you need to produce them yourself:

raw_cd=(1150 1151)
for i in $(seq "${#raw_cd[@]}")
do
  echo "$i": "${raw_cd[$i - 1]}"
done

will produce

1: 1150
2: 1151

Even better, you can directly get keys like this, without seq (this will work even on associative arrays):

raw_cd=(1150 1151)
for i in "${!raw_cd[@]}"
do
  echo "$i": "${raw_cd[$i]}"
done
Sign up to request clarification or add additional context in comments.

9 Comments

How can I achieve this by using for loop?
I don't understand — I just showed you two (EDIT: three) snippets, each of which uses a for loop.
tried it but its not working n giving error.
If you are getting an error, you should also say what that error is, then maybe I can figure out what is happening. If you don't, the most that I can say is that it works for me — I copy-pasted my output, I didn't invent it.
Maybe I know what it is — the second snippet might be zsh-specific. The first snippet should work in both bash and zsh
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.