来自文件内容的命令行参数
如何将文件内容转换为Unix命令的参数?
将参数转换为文件内容的步骤如下:
echo ABC > file.txt 但是另一个方向?
 如果你的shell是bash(其他), $(cat afile)的快捷方式是$(< afile) ,所以你可以这样写: 
 mycommand "$(< file.txt)" 
在“命令replace”部分的bash手册页中logging。
 改变,从标准input读取你的命令,所以: mycommand < file.txt 
 如前所述,您可以使用反引号或$(cat filename) 。 
什么没有提到,我认为重要的是要注意,是你必须记住shell将按照空格分割该文件的内容,把它发现的每个“单词”作为一个参数。 尽pipe你可以用引号将命令行参数括起来,以便它可以包含空格,转义序列等,但是从文件中读取不会做同样的事情。 例如,如果您的文件包含:
 a "bc" d 
你会得到的论据是:
 a "b c" d 
如果你想把每一行作为参数,使用while / read / do结构:
 while read i ; do command_name $i ; done < filename 
你使用反引号来做到这一点:
 echo World > file.txt echo Hello `cat file.txt` 
 command `< file` 
会将文件内容传递给stdin上的命令,但会去掉换行符,这意味着你不能单独遍历每一行。 为此,你可以写一个'for'循环的脚本:
 for i in `cat input_file`; do some_command $i; done 
如果你想以一种可靠的方式来实现这个function,那么对于每一个可能的命令行参数(带空格的值,带有换行符的值,带有引号字符的值,不可打印的值,带有glob字符的值等等)更有意思的。
要写入一个文件,给定一个参数数组:
 printf '%s\0' "${arguments[@]}" >file 
  ……用"argument one" , "argument two"等取代。 
从该文件读取并使用其内容(在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语言将NUL分隔的内容转换为eval -safe格式: 
 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 "$@" 
以下是我如何将文件的内容作为parameter passing给命令:
 ./foo --bar "$(cat ./bar.txt)" 
在我的bash shell中,以下就像一个魅力:
 cat input_file | xargs -I % sh -c 'command1 %; command2 %; command3 %;' 
其中input_file是
 arg1 arg2 arg3 
很明显,这允许你从input_file的每行执行多个命令,这是我在这里学到的一个很好的小技巧。