如何从文件中读取命令的位置参数

时间:2013-09-03 04:07:38

标签: bash io-redirection

  

Q1.i想要从文件中读取命令的位置参数。       手段       some_command位置参数...       我该怎么做?

Q2. what is this line means :
    echo $(0<file_name)
   i can echo contents of file name using this command but when
   i do echo 0<file_name it does nothing kindly clear my doubt.

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容读取位置参数:

set -- $(<file_name)

...其中$(<xyz)$(0<xyz)等同于以下基础:

set -- `cat xyz`

答案 1 :(得分:0)

A1)使用getopts as suggested by the BashFAQ

A2)$()执行命令。与&#34;``&#34;

相同

答案 2 :(得分:0)

A1:在您的脚本中,根据文件内容设置位置参数:

read -rd '' -a R < filename  ## Reads input from file, and splits it with the values from IFS ($' \t\n'). This doesn't only read a line. With no delimeter (-d ''), it reads the whole input.
set -- "${R[@]}"  ## "${R[@]}" will expand to multiple arguments depending on the values of the array R. This is just the common way to transfer the contents of an array to the positional parameters.

使用$()$(<file_input)等格式时,展开的值也会受到分词的影响,但可能会因路径名扩展而发生变化。要阻止路径名扩展,请使用noglobset -o noglobset -f)将其停用,或者只使用read -a

A2:根据bash手册:命令替换$(cat文件)可以替换为等效但更快的$(&lt; file)。。它前面的可选数字,例如0似乎是一个自定义输入文件描述符实际上似乎没有区别:echo "$(<file)"echo "$(40<file)"是一样的。

但当我做echo 0<file_name时它什么都不做

它不会,因为它已经是file_name输入的重定向形式。并且echo仅根据其参数或参数echo arg1 arg2 ...发送输出,而不是像cat:cat < file_name这样的输入。

备注:

  • 建议您只为echo使用一个参数,并在双引号""内连接您的字符串。
  • 0<也与<相同,默认输入使用fd 0。