Bash 像解析参数一样解析变量?
在Bash中有没有一种方法(不调用第二个脚本)可以像解析命令行参数一样解析变量?我希望能够通过引用等方式对它们进行分组 例如:Bash 像解析参数一样解析变量?,bash,parsing,arguments,Bash,Parsing,Arguments,在Bash中有没有一种方法(不调用第二个脚本)可以像解析命令行参数一样解析变量?我希望能够通过引用等方式对它们进行分组 例如: this="'hi there' name here" for argument in $this; do echo "$argument" done 哪些应该打印(但显然不打印) 我自己算出了一半的答案。考虑下面的代码: this="'hi there' name here" eval args=($this) for arg in "${args[@
this="'hi there' name here"
for argument in $this; do
echo "$argument"
done
哪些应该打印(但显然不打印)
我自己算出了一半的答案。考虑下面的代码:
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"
eval args=($this)
for arg in "${args[@]}"; do
echo "$arg"
done
它将打印所需的输出
hi there
name
here
使用
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
使用
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
不要将参数存储在字符串中。阵列就是为了这个目的而发明的:
this=('hi there' name here)
for argument in "${this[@]}"; do
echo "$argument"
done
如果您可以控制此
,强烈建议您使用此方法。如果您不这样做,那就更有理由不使用eval
,因为非预期的命令可以嵌入this
的值中。例如:
$ this="'hi there'); echo gotcha; foo=("
$ eval args=($this)
gotcha
不那么邪恶的事情很简单,比如
this=“'hi there'*”
eval
将把*
展开为模式,匹配当前目录中的每个文件。不要将参数存储在字符串中。阵列就是为了这个目的而发明的:
this=('hi there' name here)
for argument in "${this[@]}"; do
echo "$argument"
done
如果您可以控制此
,强烈建议您使用此方法。如果您不这样做,那就更有理由不使用eval
,因为非预期的命令可以嵌入this
的值中。例如:
$ this="'hi there'); echo gotcha; foo=("
$ eval args=($this)
gotcha
不那么邪恶的事情很简单,比如
this=“'hi there'*”
eval
将把*
扩展为一个模式,匹配当前目录中的每个文件。这个问题中有一些建议-这个问题中有一些建议-我从read
提示符或Zenity对话框中获得输入。有没有办法把它放到数组中?我从read
提示符或Zenity对话框中获取输入。有没有办法把它放到一个数组中?