比如说,我有一个文件foo.txt,指定了N个参数

arg1
arg2
...
argN

我需要传递给命令my_command

如何使用文件的行作为命令的参数?


当前回答

如果你的shell是bash, $(cat afile)的快捷方式是$(< afile),所以你可以这样写:

mycommand "$(< file.txt)"

bash手册页中的“命令替换”部分中有详细说明。

或者,让你的命令从stdin读取,这样:mycommand < file.txt

其他回答

这两种解决方案即使在行中有空格时也有效:

readarray -t my_args < foo.txt
my_command "${my_args[@]}"

如果readarray不起作用,用mapfile代替它,它们是同义词。

我以前尝试过下面这个,但当my_command是一个脚本时有问题:

xargs -d '\n' -a foo.txt my_command

我建议使用:

command $(echo $(tr '\n' ' ' < parameters.cfg))

只需修改结束行字符并将其替换为空格,然后使用echo将结果字符串作为可能的单独参数推入。

你可以使用反勾:

echo World > file.txt
echo Hello `cat file.txt`

如果你的shell是bash, $(cat afile)的快捷方式是$(< afile),所以你可以这样写:

mycommand "$(< file.txt)"

bash手册页中的“命令替换”部分中有详细说明。

或者,让你的命令从stdin读取,这样:mycommand < file.txt

在我的bash shell下面的工作就像一个魅力:

cat input_file | xargs -I % sh -c 'command1 %; command2 %; command3 %;'

input_file在哪里

arg1
arg2
arg3

显然,这允许您对input_file中的每一行执行多个命令,这是我在这里学到的一个不错的小技巧。