2016-02-26 63 views
0

我需要有一个可变的shell命令在一个xargs的呼叫使用指定的shell命令失败。xargs的打电话的时候,用一个变量

... xargs的-I {} SH -c 命令 ...

我发现当命令是 '文字',但是当我通过一个shell变量指定失败xargs的工作。

任何建议排除此故障?

下面是示例代码。

## xargs call with literal shell command 

# works; creates file abcd1234.txt containing string 'abcd1234' 
echo 'abcd1234' | xargs -I {} -n 1 sh -c 'echo {} | grep "\d" > {}.txt' 

## xargs call with variable as shell command 

# create shell command to give to xargs 
cmd1='echo' 
cmd2='grep "\d"' 
command=${cmd1}' {} | '${cmd2}' > {}.txt' 

# returns the literal command that works: echo {} | grep "\d" > {}.txt 
echo $command 

# fails 
echo 'abcd1234' | xargs -I {} -n 1 sh -c $(echo $command) 

回答

1

尝试

echo 'abcd1234' | xargs -I {} sh -c "$command" 

注:我已经移除的命令-n 1,因为它违背-I,这意味着行由行处理。

你没有使用你的周围命令替换$(...),这使得外壳采用分词(分裂成空白符),这意味着多个论点放在-c选项,而不是一个后双引号单个命令字符串。

除此之外,不需要涉及命令替换:直接使用双引号变量("$command")就足够了。

相关问题