0

For some reason this script is not adding new lines. It prints - 2 - 2 - 2 all on one line even though there is a line break in my variable assignment. I am using bash on mac.

config="1,2,3
1,2,3
1,2,3
"

docker_volumes=""

IFS=$'\n'
for line in $config; do
  docker_volume=$(echo "$line" | cut -f 2 -d ',')
  # the line break below is being ignored
  docker_volumes="$docker_volumes
  - $docker_volume"
done

# prints all on one line
echo $docker_volumes
cooldude101
  • 1,215
  • 2
  • 14
  • 29
  • Quoting from the bash manual, under `Command Substitution`: which is what the `$( )` construct means, `Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing new-lines deleted.` see https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html – Jetchisel Jun 12 '20 at 08:05
  • the linebreak ignored is `"docker_volumes="$docker_volumes - $docker_volume"` which does not contain a `$()` – cooldude101 Jun 12 '20 at 08:08
  • Don't read lines with for, https://mywiki.wooledge.org/BashPitfalls#pf1, https://shellcheck.net – Jetchisel Jun 12 '20 at 08:11
  • so what's the best way to do it? The link you sent explains how to iterate over a list of files, whereas im interating over a list of lines – cooldude101 Jun 12 '20 at 08:15
  • Change `echo $docker_volumes` into `echo "$docker_volumes"` : whitespaces are stripped when you refer to a variable outside of quotes – Aaron Jun 12 '20 at 08:16
  • @cooldude101, a list is a list regardless if it is files, strings, lines, etc. and yeah shellcheck should tell you to quote the variables. – Jetchisel Jun 12 '20 at 08:17
  • @Aaron thanks, that was the issue – cooldude101 Jun 12 '20 at 08:17
  • @Jetchisel no it's not, nowhere in that article it explains how to iterate over lines that contain spaces without the use of IFS – cooldude101 Jun 12 '20 at 08:18
  • And to answer your question about iterating over a list of lines, I would use `while IFS=$'\n' read -r line; do ...; done <<<"$config"` – Aaron Jun 12 '20 at 08:19
  • @cooldude101, here https://mywiki.wooledge.org/BashFAQ/001 – Jetchisel Jun 12 '20 at 08:22

0 Answers0