4

Is it possible to format this sample:

for i in string1 string2 stringN
do
 echo $i
done

to something similar to this:

for i in 
string1
string2
stringN
do
 echo $i
done

EDIT: Sorry for confusion, didn't realize that there was different methods of executing script - sh <scriptname> versus bash <scriptname> and also this thing which I cannot name right now - #!/bin/sh and #!/bin/bash :)

  • What is the problem you are trying to solve? – Jesse_b Jun 20 '18 at 18:15
  • Did you try what you're asking to see whether it'd work? – DopeGhoti Jun 20 '18 at 18:15
  • @Jesse_b readability and managebility of bunch of strings – user296353 Jun 20 '18 at 18:40
  • @DopeGhoti yes I did – user296353 Jun 20 '18 at 18:42
  • @waayee: In that case an array is your best bet. See Glenn Jackman's answer. – Jesse_b Jun 20 '18 at 18:45
13

Using arrays in bash can aid readability: this array syntax allows arbitrary whitespace between words.

strings=(
    string1
    string2
    "string with spaces"
    stringN
)
for i in "${strings[@]}"; do
    echo "$i"
done
  • This seems most elegant, but unfortunately gives error: Syntax error: "(" unexpected – user296353 Jun 20 '18 at 18:38
  • 1
    @waayee, then you're not running it in Bash. Remember that sh isn't necessarily Bash, and especially isn't on Debian and Ubuntu. – ilkkachu Jun 20 '18 at 18:44
  • 1
    @ilkkachu Think I get it now - must run "bash <scriptname>" not "sh <scriptname>" :) – user296353 Jun 20 '18 at 19:08
  • @waayee, or put a proper hashbang/shebang line and run it like an executable. Required reading: Does the shebang determine the shell which runs the script? – ilkkachu Jun 20 '18 at 19:17
  • 1
    @rrrrr, your questions are probably answered here: stackoverflow.com/q/12314451/7552 – glenn jackman Nov 17 '18 at 1:01
4

You can escape the linebreak with a backslash:

$ for i in \
> hello \
> world
> do
> echo $i
> done
hello
world
$
2

You may escape the newlines before/after each item that you loop over:

for i in \
    string1 \
    string2 \
    stringN
do
   printf '%s\n' "$i"
done

Or, for this simple example:

printf '%s\n' string1 string2 stringN

which has the same result.

Related:

Variation using a bash array:

strings=(
    string1
    string2
    stringN
)

printf '%s\n' "${strings[@]}"
1

If switching to zsh is an option:

for string (
  string1
  'other string'
  etc..
) printf '%s\n' "$string"
0

You can use the loop command, available here, like so:

$ loop "echo $ITEM" --for string1,string2,string3

or, if you have a list as a file:

$ cat file_list.txt | loop "echo $ITEM"

Your Answer

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