假设我有一个非常简单的shell脚本'foo':
#!/bin/sh
echo $@
Run Code Online (Sandbox Code Playgroud)
如果我像这样调用它:
foo 1 2 3
Run Code Online (Sandbox Code Playgroud)
它愉快地打印:
1 2 3
Run Code Online (Sandbox Code Playgroud)
但是,假设我的一个参数是双引号括起来并包含空格:
foo 1 "this arg has whitespace" 3
Run Code Online (Sandbox Code Playgroud)
foo愉快地打印:
1 this arg has whitespace 3
Run Code Online (Sandbox Code Playgroud)
双引号被剥夺了!我知道shell认为它帮我一个忙,但是...我想得到原始版本的论点,不受shell解释的影响.有没有办法这样做?
首先,你可能想要引用版本$@,即"$@".要感受差异,请尝试在字符串中放置多个空格.
其次,引号是shell语法的元素 - 它对你不利.为了保护它们,你需要逃避它们.例子:
foo 1 "\"this arg has whitespace\"" 3
foo 1 '"this arg has whitespace"' 3
Run Code Online (Sandbox Code Playgroud)
双引号 $@:
#!/bin/sh
for ARG in "$@"
do
echo $ARG
done
Run Code Online (Sandbox Code Playgroud)
然后:
foo 1 "this arg has whitespace" 3
Run Code Online (Sandbox Code Playgroud)
会给你:
1
this arg has whitespace
3
Run Code Online (Sandbox Code Playgroud)
我要做的就是用空格引用收到的所有参数,这可能对您的情况有帮助。
for x in "${@}" ; do
# try to figure out if quoting was required for the $x
if [[ "$x" != "${x%[[:space:]]*}" ]]; then
x="\""$x"\""
fi
echo $x
_args=$_args" "$x
done
echo "All Cmd Args are: $_args"
Run Code Online (Sandbox Code Playgroud)
您需要引用引号:
foo 1 "\"this arg has whitespace\"" 3
Run Code Online (Sandbox Code Playgroud)
或者(更简单地)
foo 1 '"this arg has whitespace"' 3
Run Code Online (Sandbox Code Playgroud)
您需要用双引号引起来,以确保 shell 在解析单词参数时不会删除它们。
| 归档时间: |
|
| 查看次数: |
6846 次 |
| 最近记录: |