Bash 中有没有办法(不调用第二个脚本)来解析变量,就好像它们是命令行参数一样?我希望能够按引号等对它们进行分组。
例子:
this="'hi there' name here"
for argument in $this; do
echo "$argument"
done
应该打印(但显然没有)
hi there
name
here
我自己想出了一个半答案。考虑以下代码:
this="'hi there' name here"
eval args=($this)
for arg in "${args[@]}"; do
echo "$arg"
done
打印所需的输出
hi there
name
here
不要将参数存储在字符串中。为此目的发明了数组:
this=('hi there' name here)
for argument in "${this[@]}"; do
echo "$argument"
done
如果您可以控制this
. 如果你不这样做,那就更有理由不使用eval
,因为意外的命令可以嵌入到this
. 例如:
$ this="'hi there'); echo gotcha; foo=("
$ eval args=($this)
gotcha
不那么邪恶是简单的事情this="'hi there' *"
。eval
将扩展*
为模式,匹配当前目录中的每个文件。
使用gsed -r
:
echo "$this" | gsed -r 's/("[^"]*"|[^" ]*) */\1\n/g'
"hi there"
name
here
使用egrep -o
:
echo "$this" | egrep -o '"[^"]*"|[^" ]+'
"hi there"
name
here
纯 BASH 方式:
this="'hi there' name here"
s="$this"
while [[ "$s" =~ \"[^\"]*\"|[^\"\ ]+ ]]; do
echo ${BASH_REMATCH[0]}
l=$((${#BASH_REMATCH[0]}+1))
s="${s:$l}"
done
"hi there"
name
here