Can I make a for loop on variables in a bash shell?

I am studying the shell and I want to be able to iterate over some variables. I can't find anywhere where anyone has done this, so I'm not sure if this is possible.

Basically, I just want to save myself the trouble by using the same sed command for each of these variables. However, the code is clearly not working. My question is: is it possible to iterate over variables, and if not, how should I do it?

title="$(echo string1)"
artist="$(echo string2)"
album="$(echo string3)"

for arg in title artist album do
    $arg="$(echo "$arg" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')"
done

here is the error:

line 12: syntax error near unexpected token `$arg="$(echo "$arg" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')"'
+3
source share
1 answer

Your problem is not in the cycle, but in the task. The variable name must be literal in the task, i.e. You can write title=some_value, but not $arg=some_value.

eval. $arg ( arg, $arg), eval.

new_value="$(eval printf %s \"\$$arg\" | …)"
eval $arg=\$new_value

, bash/ksh/zsh, - typeset. bash, , . , ${!arg}; bash.

typeset $arg="$(printf %s "${!arg}" | …)"

:

  • title="$(echo string1)" - title="string1", , , string1, -.
  • do (; ).

bash/ksh/zsh, ${VARIABLE//PATTERN/REPLACEMENT}.

title="string1"
artist="string2"
album="string3"
for arg in title artist album; do
  eval value=\$$arg
  value=${value//&/&amp;}
  value=${value//</&lt;}
  value=${value//>/&gt;}
  eval $arg=\$value
done
+5

All Articles