在Bash中将IFS设置为非空白字符的单词拆分 [英] Word splitting in Bash with IFS set to a non-whitespace character

查看:123
本文介绍了在Bash中将IFS设置为非空白字符的单词拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Bash 教程,特别是分词的主题.

I'm going through a Bash tutorial, and specifically the subject of word splitting.

此脚本称为"args",有助于演示分词示例:

This script, called "args", helps demonstrate word splitting examples:

#!/usr/bin/env bash
printf "%d args:" $#
printf " <%s>" "$@"
echo

一个例子:

$ ./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.

但是,当我将IFS替换为非空白字符(例如:)时,如果我直接将字符串作为参数传递,则脚本不会执行分词.

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>

但是,如果我(1)将字符串分配给变量,然后(2)通过参数扩展将字符串传递给脚本,则脚本对同一字符串执行分词./p>

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>

为什么?具体来说,为什么在未设置IFS且定界符为空白字符时将字符串作为参数传递却进行单词拆分,而在将IFS设置为非空白字符时为什么不这样做呢?

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?

当我使用read代替此脚本时,相同的字符串也会按预期进行分词.

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

推荐答案

您可以阅读有关分词的更多信息

You can read more about word splitting here.

shell扫描参数扩展,命令替换, 和算术扩展,这在双引号中不会出现.

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

当您将裸字符串one:two:three作为IFS设置为:的参数传递时,Bash不会进行单词拆分,因为裸字符串不是参数扩展,命令替换之一 ,或算术扩展上下文.

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>

作为记录read命令除非将IFS设置为空字符串,否则在读取的每一行上都会进行分词.

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

这篇关于在Bash中将IFS设置为非空白字符的单词拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆