-2

I have the following code:

script_list=$'1 a\n2\n3'
old_IFS="${IFS}"
IFS=$'\n'
for line in "${script_list}"; do
    echo "__${line}__";
done
IFS="${old_IFS}"

which shall produce:

__1 a__
__2__
__3__

However, instead it gives me:

__1 a
2
3__

I double quoted "${script_list}" because it can contain spaces (see: https://stackoverflow.com/a/10067297). But I believe this is also where the problem lies, because when I remove the double quotes around it, it works as expected.

What am I missing?

edit: As Cyrus suggested, I ran the code at ShellCheck and it tells me:

$ shellcheck myscript
 
Line 5:
for line in "${script_list}"; do
            ^-- SC2066: Since you double quoted this, it will not word split, and the loop will only run once.

Is it safe to simply remove the double quotes or do I need to be careful with that?

TimFinnegan
  • 583
  • 5
  • 17
  • 1
    You ask `Why is my line read not working as expected in bash?` so you have the answer `Since you double quoted this, it will not word split, and the loop will only run once`. || `Is it safe to simply remove the double quotes or do I need to be careful with that?` define "safe". It will be "safe" as in the loop will execute. But be aware of filename expansion. || Are you asking XY question? – KamilCuk Jun 04 '21 at 04:54
  • It is safe as long as script_list doesn't contain globbing characters. But I have no idea what you're doing there. Why do you need this? What is the point? – oguz ismail Jun 04 '21 at 04:58

1 Answers1

1

I double quoted "${script_list}" because it can contain spaces

This is only done to prevent the shell from splitting the string at spaces. However you explicitly tell the shell (by setting IFS) that your IFS is now a newline, not a space. The shell would split by default here on newlines, not on spaces, unless you quote it. Hence, remove the quotes.

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • Thanks! I did not knew about this yet. Here is the bash manual entry in case anyone else likes to look it up: https://www.gnu.org/software/bash/manual/bash.html#Word-Splitting – TimFinnegan Jun 04 '21 at 11:12