0

I have two examples of a bash script. All I do is just use sed to replace some strings in a file. The file is specified when the script is run. So, you would run it like ./replace_file.sh input_file.

hug="g h 7"

for elm in $hug
do
  echo "replacing $elm"
  sed -i'_backup' "s/$elm/BOO/g" $1
done

and

hug=('g' 'h' '7')

for elm in $hug
do
  echo "replacing $elm"
  sed -i'_backup' "s/$elm/BOO/g" $1
done

The first script above, echos the following:

replacing g
replacing h
replacing 7

But, the second one stops after replace g. It is unclear to me why. Can someone please shed some light?

Thank you.

4
  • (why exactly did you tag PHP here? - just curious) Commented Feb 13, 2016 at 7:36
  • I meant to do cli typo sorry! Commented Feb 13, 2016 at 7:40
  • 1
    for elm in ${hug[@]} in the case of the array... You can quote "${hug[@]}" to preserve whitespace in the elements (if they have any -- you don't) Attempting to call an array without braces, e.g. {...[@]}, you are simply referencing the first element of the array, 'g' in your case. Commented Feb 13, 2016 at 7:48
  • hug="g h 7" doesn't create an array at all; it just creates a string with whitespace in it. Commented Feb 13, 2016 at 16:32

1 Answer 1

2

As set forth in the comment, when you attempt to iterate over the elements in the array by calling for elm in $hug, you are simply referencing the first element in the array. To iterate over the elements in the array, you use the array syntax, e.g. ${array[@]} to access each element sequentially (and you can quote the array to preserve whitespace in the elements.) In your case you need only:

#!/bin/bash

hug=('g' 'h' '7')

for elm in ${hug[@]}
do
echo "replacing $elm"
# sed -i'_backup' "s/$elm/BOO/g" $1
done

Output

$ bash arrayiter.sh
replacing g
replacing h
replacing 7
Sign up to request clarification or add additional context in comments.

3 Comments

Needs quotes around the ${hug[@]} to avoid string-splitting. Try hug=( "foo bar" "baz qux" ) to observe the bug in this as currently written.
Now I'm confused. I noted you should quote to preserve whitespace (prevent word-splitting), but his elements are 'g', 'h', and '7'. so I left it as a note. Did I miss something?
If the elements of the array do not contain whitespace, then it doesn't matter if you quote it or not; the result is the same. But if even one item does contain whitespace, it is crucial that you quote the expansion.

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.