bash:如何给function传参数

时间:2021-03-13 16:41:05

给shell里的函数(function)传递参数有2种方式:

第一种方式:
在function里直接通过$1,$2,etc.来获取参数:

例:
建立一个文件“file.txt”在shell里创建一个函数并调用:

file.txt:

funcTest.sh:

该shell的执行结果:

从上面的结果可以看出通过这种传递方式grep结果里的换行已经被无视了,本来应该是3行*3个参数,直接被当做9个参数了。

另外,$0在这里指的是shell脚本名。

 

第二种方式:

使用awk:

 

例:

执行结果:

可以看到,awk可以分3次进行处理,相当于调用了3遍myfunc2.

此外还有一点,$0在这里指的是本次调用的所有参数。

 

注意点:

第一种方式不支持管道传参,使用“grep china file.txt|myfunc”将得不到你想要的结果。

相反第二种方式(awk方式)只支持管道传参,而不支持“myfunc2 `grep china file.txt`”的调用方式。

--------------------------------------------------------------------------------------------------------------------

提示:

Built-in Shell Variables:

 

$# : Number of command-line arguments.

$- : Options currently in effect (supplied on command line or to set). The shell sets some options automatically.

$? : Exit value of last executed command.

$$ : Process number of the shell.

$! : Process number of last background command.

$0 : First word; that is, the command name. This will have the full
     pathname if it was found via a PATH search.

$n : Individual arguments on command line (positional parameters).
     The Bourne shell allows only nine parameters to be referenced
     directly (n = 1–9); Bash allows n to be greater than 9
     if specified as ${n}.

$*, $@ : All arguments on command line ($1 $2 …).

"$*" : All arguments on command line as one string ("$1 $2…"). The
     values are separated by the first character in $IFS.

"$@" : All arguments on command line, individually quoted ("$1" "$2" …).

$_ : Temporary variable; initialized to pathname
     of script or program being executed.
     Later, stores the last argument of previous
     command. Also stores name of matching
     MAIL file during mail checks.