比如说,我有一个文件foo.txt,指定了N个参数
arg1
arg2
...
argN
我需要传递给命令my_command
如何使用文件的行作为命令的参数?
比如说,我有一个文件foo.txt,指定了N个参数
arg1
arg2
...
argN
我需要传递给命令my_command
如何使用文件的行作为命令的参数?
当前回答
如果您希望以一种适用于所有可能的命令行参数(带有空格的值、带有换行符的值、带有文字引号的值、不可打印的值、带有glob字符的值等)的健壮方式来执行此操作,则会变得更加有趣。
写入文件,给定一个参数数组:
printf '%s\0' "${arguments[@]}" >file
…替换为“论点一”、“论点二”等。
要从该文件读取并使用其内容(在bash、ksh93或其他最新的带有数组的shell中):
declare -a args=()
while IFS='' read -r -d '' item; do
args+=( "$item" )
done <file
run_your_command "${args[@]}"
要从该文件读取并使用其内容(在没有数组的shell中;注意,这将覆盖你的本地命令行参数列表,因此最好在函数内部完成,这样你就覆盖了函数的参数而不是全局列表):
set --
while IFS='' read -r -d '' item; do
set -- "$@" "$item"
done <file
run_your_command "$@"
注意-d(允许使用不同的行结束分隔符)是非posix扩展,没有数组的shell也可能不支持它。如果是这样的话,你可能需要使用非shell语言将null分隔的内容转换为eval安全的形式:
quoted_list() {
## Works with either Python 2.x or 3.x
python -c '
import sys, pipes, shlex
quote = pipes.quote if hasattr(pipes, "quote") else shlex.quote
print(" ".join([quote(s) for s in sys.stdin.read().split("\0")][:-1]))
'
}
eval "set -- $(quoted_list <file)"
run_your_command "$@"
其他回答
下面是我如何将文件内容作为参数传递给命令:
./foo --bar "$(cat ./bar.txt)"
如果您希望以一种适用于所有可能的命令行参数(带有空格的值、带有换行符的值、带有文字引号的值、不可打印的值、带有glob字符的值等)的健壮方式来执行此操作,则会变得更加有趣。
写入文件,给定一个参数数组:
printf '%s\0' "${arguments[@]}" >file
…替换为“论点一”、“论点二”等。
要从该文件读取并使用其内容(在bash、ksh93或其他最新的带有数组的shell中):
declare -a args=()
while IFS='' read -r -d '' item; do
args+=( "$item" )
done <file
run_your_command "${args[@]}"
要从该文件读取并使用其内容(在没有数组的shell中;注意,这将覆盖你的本地命令行参数列表,因此最好在函数内部完成,这样你就覆盖了函数的参数而不是全局列表):
set --
while IFS='' read -r -d '' item; do
set -- "$@" "$item"
done <file
run_your_command "$@"
注意-d(允许使用不同的行结束分隔符)是非posix扩展,没有数组的shell也可能不支持它。如果是这样的话,你可能需要使用非shell语言将null分隔的内容转换为eval安全的形式:
quoted_list() {
## Works with either Python 2.x or 3.x
python -c '
import sys, pipes, shlex
quote = pipes.quote if hasattr(pipes, "quote") else shlex.quote
print(" ".join([quote(s) for s in sys.stdin.read().split("\0")][:-1]))
'
}
eval "set -- $(quoted_list <file)"
run_your_command "$@"
你可以使用反勾:
echo World > file.txt
echo Hello `cat file.txt`
这两种解决方案即使在行中有空格时也有效:
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