1

Example: You normally list values in a horizontal layout

for var in 0 1 2 3 4 5 6 7 8 9 do echo $var done

It would be nice for version control and readability purposes to enter each list item on its own line. Is this possible?

You can't do the following, with or without /r/n:

for var in 0 1 2 3 4 5 6
7 8 9 do echo $var done

Interestingly enough, this almost works (same regardless of single or double quote):

for var in '0 1 2 3 4 5 6 7 8 9' do echo $var done

outputting:

-bash: demo.sh: line 11: syntax error near unexpected token ` '0 1 2 3 4 5 6 7 8 9'' -bash: demo.sh: line 11: ` 9''

This does not work, regardless of single or double quote.

for var in "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" do echo $var done

1

Give a try to this tested version:

#!/bin/bash --
for var in  \
1 \
2 \
3 \
4 \
6 \
 ; do
  printf "%s\n" "${var}"
done

the for loop splits by default a string containing (spaces) and \n into separate elements.

' used in your for loop instructs the shell (in your version) to consider the parameter as one single value, a string containing several lines.

The test:

$ ./list.sh
1
2
3
4
6

The first version for reference:

#!/bin/bash --
listint='
1
2
3
4
6
'

for var in ${listint} ; do
  printf "%s\n" "${var}"
done

The ' enable to define string over multiple lines, including the \n.

2
  • Hey hey, that worked! Can you elaborate a bit on what's happening to enable this? – Kevin Suttle Apr 12 '16 at 20:11
  • 1
    @KevinSuttle the example at the top had been updated with something very close to your version. – Jay jargot Apr 12 '16 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.