bash:如何给function传参数

给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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值