Home>

Hello.
While studying shell scripts (bash), the behavior of for statements when IFS variables are changed
I have a question because I have a problem.

bash version

GNU bash, version 4.4.19 (3) -release (i686-pc-msys)
GNU bash, version 4.2.46 (2) -release (x86_64-redhat-linux-gnu)

What you did

(1) First, the following shell was executed with $IFS set to default (blank, line feed, horizontal tab).

for i in abc def
do
    echo string = $i
done
Execution result
string = abc
string = def


(2) Next, I changed $IFS to "quote" and executed a similar shell.

IFS = /
for i in abc // def
do
    echo string = $i
done
Execution result
string = abc def
Questions
  1. As for the execution result of (2), it was assumed that it will be output with a delimiter as shown in (1).
    However, the line feed is not actually output because it is a new line, and $i seems to contain the input value as it is (abc def). Why is this?
  2. For
  3. (2), how can I make a line break with a delimiter like the execution result of (1)?
  • Answer # 1

    Man bash makes it difficult to interpret the sentence, but words are re-separated (once separated by whitespace), brace expansion, tilde expansion, parameter and variable expansion, command substitution It seems only after arithmetic expression expansion.
    However, in practice, there is no word re-breaking in the results of brace expansion or tilde expansion, and it seems that re-breaking in IFS occurs only in the results of parameter and variable expansion, command substitution, and arithmetic expression expansion. . And documented.

    If you want to separate IFS, you need to put it in a variable.

    IFS = /
    FOO = abc // def
    for i in $FOO
    do
        echo string = $i
    done