Pregunta

I have very simple script:

$ cat $$.sh
#!/bin/sh -x

VAR="one two
three four"

for i in $VAR ; do
    echo $i
done
$ 

run output:

$ sh -x $$.sh
+ VAR='one two
three four'
+ for i in '$VAR'
+ echo one
one
+ for i in '$VAR'
+ echo two
two
+ for i in '$VAR'
+ echo three
three
+ for i in '$VAR'
+ echo four
four
$

seems like it's looking for a space and I need for it to look for line break instead

¿Fue útil?

Solución

If you're reading multiple lines, line-by-line, then a while read loop is a common way to do this:

VAR="one two
three four"

while IFS='' read -r i ; do
    echo "$i"
done <<< "$VAR"

This produces:

one two
three four

Note in this example, the while loop is taking input from the $VAR variable using a bash here-string redirection. But this could just as easily be a redirection from a file or pipe.

Otros consejos

The shell would perform word splitting on space and newline by default. Set IFS to a newline instead. Moreover, if you are using for then it's better to turn off globbing (as suggested by @CharlesDuffy):

set -o noglob

VAR="one two
three four"

IFS=$'\n'
for i in $VAR ; do
    echo $i
done

This would produce:

one two
three four
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top