按索引列出的bash函数参数-头部和回波之间的差异

按索引列出的bash函数参数-头部和回波之间的差异,bash,Bash,我对访问函数参数时“head”命令中的奇怪行为感到困惑。 代码如下: function fun1 { echo $1; head $1; } 下面是两个不同函数调用的输出 echo "asasa" | fun1 --- output start --- asasa --- end --- 当传递参数时: echo "asasa" | fun1 "var1" --- output start --- var1 head: cannot open `var1' for reading: No

我对访问函数参数时“head”命令中的奇怪行为感到困惑。 代码如下:

function fun1 { echo $1; head $1; }
下面是两个不同函数调用的输出

echo "asasa" | fun1
--- output start ---

asasa
--- end ---
当传递参数时:

echo "asasa" | fun1 "var1"
--- output start ---
var1
head: cannot open `var1' for reading: No such file or directory
--- end ---

访问参数1($1)中到底发生了什么,为什么head和echo对它的解释非常不同

head
仅当stdin的参数为空时才从其读取输入。既然你给它传递了一个论点,它就试着去读它

Usage: head [OPTION]... [FILE]...
Print the first 10 lines of each FILE to standard output.
With more than one FILE, precede each with a header giving the file name.
With no FILE, or when FILE is -, read standard input.

head
仅当stdin的参数为空时才从其读取输入。既然你给它传递了一个论点,它就试着去读它

Usage: head [OPTION]... [FILE]...
Print the first 10 lines of each FILE to standard output.
With more than one FILE, precede each with a header giving the file name.
With no FILE, or when FILE is -, read standard input.

$1
始终引用在命令行上传递的第一个参数,它与通过stdin的任何输入分开

head
需要一个或多个文件名作为其(非选项)参数-如果没有文件名,则从stdin读取输入。(许多处理文件内容的实用程序都是这样操作的)

echo“asasa”| fun1
。。。仅标准输入,无参数(
$1
未设置):

  • echo$1
    回显空行(仅
    \n
    ),因为未设置
    $1
  • head$1
    从stdin(
    asasa
    )回显(最多10行):因为
    $1
    未设置,就好像没有参数传递给
    head
    ,所以它从stdin读取
echo“asasa”| fun1“var1”
。。。stdin输入和1参数:
$1
设置为
var1

  • echo$1
    echo
    var1
    ,分配给
    $1
    的值
  • head$1
    报告错误,因为
    var1
    被解释为文件名,并且不存在这样的文件;在这种情况下,将忽略标准输入
如果希望
echo
访问参数和
head
访问stdin输入,只需从
head
命令中删除
$1
参数:

function fun1 { echo $1; head; }

相反,如果您真的想处理通过参数
$1
传递的字符串,且该参数带有
head
,则必须在脚本中通过stdin显式提供该字符串(例如,通过
<1
始终指在命令行上传递的第一个参数,该参数与通过stdin的任何输入分开

head
需要一个或多个文件名作为其(非选项)参数—如果没有文件名,则从stdin读取输入。(许多处理文件内容的实用程序都是这样做的)

echo“asasa”| fun1
…仅标准输入,无参数(
$1
未设置):

  • echo$1
    回显空行(仅
    \n
    ),因为未设置
    $1
  • head$1
    从stdin(
    asasa
    )回显(最多10行):因为
    $1
    未设置,就好像没有参数传递给
    head
    ,所以它从stdin读取
echo“asasa”| fun1“var1”
…标准输入和1参数:
$1
设置为
var1

  • echo$1
    echo
    var1
    ,分配给
    $1
    的值
  • head$1
    报告一个错误,因为
    var1
    被解释为文件名,并且不存在这样的文件;在这种情况下,stdin输入被忽略
如果希望
echo
访问参数和
head
访问stdin输入,只需从
head
命令中删除
$1
参数:

function fun1 { echo $1; head; }

相反,如果您确实希望使用
head
处理通过参数
$1
传递的字符串,则必须在脚本中通过stdin显式提供该字符串(例如,通过
你也可以添加此澄清为什么
echo | fun1
没有给出任何错误。@anubhava:我不100%确定你的意思,但希望我的更新能够满足你的建议。如果没有,请告诉我。你也可以添加此澄清为什么
echo | fun1
没有给出任何错误。@anubhava:我不100%确定你的意思我的意思是,但希望我的更新能满足你的建议。如果没有,请告诉我。