比如说,我有一个文件foo.txt,指定了N个参数
arg1
arg2
...
argN
我需要传递给命令my_command
如何使用文件的行作为命令的参数?
比如说,我有一个文件foo.txt,指定了N个参数
arg1
arg2
...
argN
我需要传递给命令my_command
如何使用文件的行作为命令的参数?
当前回答
你可以使用反勾:
echo World > file.txt
echo Hello `cat file.txt`
其他回答
下面是我如何将文件内容作为参数传递给命令:
./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
这两种解决方案即使在行中有空格时也有效:
readarray -t my_args < foo.txt
my_command "${my_args[@]}"
如果readarray不起作用,用mapfile代替它,它们是同义词。
我以前尝试过下面这个,但当my_command是一个脚本时有问题:
xargs -d '\n' -a foo.txt my_command
如果你的shell是bash, $(cat afile)的快捷方式是$(< afile),所以你可以这样写:
mycommand "$(< file.txt)"
bash手册页中的“命令替换”部分中有详细说明。
或者,让你的命令从stdin读取,这样:mycommand < file.txt
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/