I'm going through a Bash tutorial, and specifically the subject of word splitting.
This script, called "args", helps demonstrate word splitting examples:
#!/usr/bin/env bash
printf "%d args:" $#
printf " <%s>" "$@"
echo
An example:
$ ./args hello world, here is "a string of text!"
5 args: <hello> <world,> <here> <is> <a string of text!>
So far so good. I understand how this works.
However, when I replace IFS with a non-whitespace character, say :
, the script does not perform word splitting if I pass the string directly as an argument.
$ ./args one:two:three
1 args: <one:two:three>
However, the script does perform word splitting on the same string if I (1) assign the string to a variable, and then (2) pass the string to the script via parameter expansion.
$ IFS=:
$ variable="one:two:three"
$ ./args $variable
3 args: <one> <two> <three>
Why? Specifically, why does passing the string as an argument undergo word splitting when IFS is unset and the delimiters are whitespace characters, but not when IFS is set to non-whitespace characters?
When I use read
instead of this script, the same string also undergoes word splitting as expected.
$ IFS=:
$ read a b c
one:two:three
$ echo $a $b $c
one two three
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…