Word splitting in Bash with IFS set to a non-whitespace character

蹲街弑〆低调 提交于 2019-11-27 06:13:42

问题


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

回答1:


You can read more about word splitting here.

The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting.

When you pass the bare string one:two:three as an argument with IFS set to :, Bash doesn't do word splitting because the bare string is not one of parameter expansion, command substitution, or arithmetic expansion contexts.

However, when the same string is assigned to a variable and the variable is passed to the script unquoted, word splitting does occur as it is a case of parameter expansion.

The same thing applies to these as well (command substitution):

$ ./args $(echo one:two:three)
3 args: <one> <two> <three>

$ ./args "$(echo one:two:three)"
1 args: <one:two:three>

As documented, read command does do word splitting on every line read, unless IFS has been set to an empty string.




来源:https://stackoverflow.com/questions/43163225/word-splitting-in-bash-with-ifs-set-to-a-non-whitespace-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!