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

arg1
arg2
...
argN

我需要传递给命令my_command

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


当前回答

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

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

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

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

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

其他回答

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

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

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

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

xargs -d '\n' -a foo.txt my_command
command `< file`

将文件内容传递给stdin上的命令,但将删除换行符,这意味着您不能单独遍历每一行。为此,你可以写一个带有' For '循环的脚本:

for line in `cat input_file`; do some_command "$line"; done

或者(多行变体):

for line in `cat input_file`
do
    some_command "$line"
done

或者(多行变体,用$()代替' '):

for line in $(cat input_file)
do
    some_command "$line"
done

引用:

对于循环语法:https://www.cyberciti.biz/faq/bash-for-loop/

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

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

input_file在哪里

arg1
arg2
arg3

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

下面是我如何将文件内容作为参数传递给命令:

./foo --bar "$(cat ./bar.txt)"

如果你所需要做的就是将文件arguments.txt的内容

arg1
arg2
argN

进入my_command arg1 arg2 argN,然后你可以简单地使用xargs:

xargs -a arguments.txt my_command

你可以在xargs调用中添加额外的静态参数,比如xargs -a arguments.txt my_command staticArg,它将调用my_command staticArg arg1 arg2 argN