比如说,我有一个文件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

其他回答

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

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

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

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中的每一行执行多个命令,这是我在这里学到的一个不错的小技巧。

我建议使用:

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

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