加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 即使使用双引号也会发生单词拆分

发布时间:2020-12-15 22:02:55 所属栏目:安全 来源:网络整理
导读:根据 http://tldp.org/LDP/abs/html/quotingvar.html Use double quotes to prevent word splitting. An argument enclosed in double quotes presents itself as a single word, even if it contains whitespace separators. 但是,我有 0 /bin/bash --versi
根据 http://tldp.org/LDP/abs/html/quotingvar.html

Use double quotes to prevent word splitting.
An argument enclosed in double quotes presents itself as a single word,
even if it contains whitespace separators.

但是,我有

0> /bin/bash --version
GNU bash,version 4.3.11(1)-release (x86_64-pc-linux-gnu)
[...]

1> cat inspect.sh 
#!/bin/bash
echo "first argument is $1"
echo "second argument is $2"

2> cat test.sh 
#!/bin/bash
set -x
./inspect.sh "hello $@"

3> ./test.sh alice bob
+ ./inspect.sh 'hello alice' bob
first argument is hello alice
second argument is bob

4> ./test.sh "alice bob"
+ ./inspect.sh 'hello alice bob'
first argument is hello alice bob
second argument is

我想知道为什么3>和4>有不同的结果?如何修改test.sh让3>具有与4>相同的输出

解决方法

答案是$@很特别.

从Bash Reference Manual部分3.4.2 Special Parameters

@

Expands to the positional parameters,starting from one. When the expansion occurs within double quotes,each
parameter expands to a
separate word. That is,“$@” is equivalent to “$1” “$2” …. If the
double-quoted expansion occurs within a word,the expansion of the
first parameter is joined with the beginning part of the original
word,and the expansion of the last parameter is joined with the last
part of the original word. When there are no positional parameters,
“$@” and $@ expand to nothing (i.e.,they are removed).

特别:

>当扩展发生在双引号内时,每个参数都会扩展为单独的单词.

>如果在一个单词中出现双引号扩展,则第一个参数的扩展与原始单词的开头部分连接,最后一个参数的扩展与原始单词的最后一部分连接.

哪个组合让你“hello”合并到第一个参数并且“”合并到最后一个参数但是每个参数都扩展为它自己的单词.

如果要将所有参数扩展为一个单词,则需要使用$*.

*

Expands to the positional parameters,it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,“$*” is equivalent to “$1c$2c…”,where c is the first character of the value of the IFS variable. If IFS is unset,the parameters are separated by spaces. If IFS is null,the parameters are joined without intervening separators.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读