存储命令时preserve分裂的说法,在可变空格 [英] Preserve argument splitting when storing command with whitespaces in variable
问题描述
我想存储在变量中的命令行,然后执行该命令行。问题是,在命令行参数已在他们的空间。如果我做
$ X ='命令复杂的论证'
$ $ X
它调用命令
与复
和参数
。我试着用$ X
以为它会preserve的说法分裂,但它只能尝试与文件名命令来执行程序复杂的论证
。我也试过引号的变化(
VS ),并使用
EXEC
,但它并没有帮助。任何想法?
编辑:的eval$ X
的几乎的工作,但如果空格分离的论点是新行,而不是空间,那么它将该行作为单独的命令。
EDIT2:额外的报价是太多了,搞得EVAL间preT换行不空格,而是作为命令分隔符的答案的解决方案的所有工作。
有关测试的目的,我定义:
$函数参数(){而[[$ 1=]!]做回声ARG:$ 1;转移;做}
这按预期工作:
的$ args1 23
ARG:1 2
ARG:3$ X =ARG 4 5 6
$ $ X
ARG:4
ARG:5
ARG:6
这并不:
$ X =ARGS \\3 4 \\5
$ $ X
ARG:3
精氨酸:4
ARG:5
一个安全的方法是将命令行存储在阵列BASH:
ARR =(命令复杂的论证)
然后执行它:
$ {ARR [@]}
要不另一个方法是使用bash函数:
cmdfunc(){
命令复杂的论证
}cmdfunc
I'd like to store a command line in a variable, and then execute that command line. The problem is, the command line has arguments with spaces in them. If I do
$ x='command "complex argument"'
$ $x
it calls command
with "complex
and argument"
. I tried using "$x"
thinking it would preserve the argument splittings, but it only tries to execute a program with the file name command "complex argument"
. I also tried variations of the quotes ('
vs "
) and using exec
, but it didn't help. Any ideas?
Edit: eval "$x"
almost works, but if the whitespaces separating arguments are newlines and not spaces, then it treats the lines as separate commands.
Edit2: The extra "
quotes were too much, and made eval interpret the newlines not as spaces, but as command delimiters. The solutions in the answers all work.
For testing purposes, I define:
$ function args() { while [[ "$1" != "" ]]; do echo arg: $1; shift; done }
This works as expected:
$ args "1 2" 3
arg: 1 2
arg: 3
$ x="arg 4 5 6"
$ $x
arg: 4
arg: 5
arg: 6
This doesnt:
$ x="args \"3 4\" 5"
$ $x
arg: "3
arg: 4"
arg: 5
A safe approach is to store your command line in a BASH array:
arr=( command "complex argument" )
Then execute it:
"${arr[@]}"
OR else another approach is to use BASH function:
cmdfunc() {
command "complex argument"
}
cmdfunc
这篇关于存储命令时preserve分裂的说法,在可变空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!