bash:如何给function传参数

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

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

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

file.txt:

chen china engineer lee china leader lynn china programmer

funcTest.sh:

myfunc () { echo "params length: $#" #“$#”会显示传给该函数的参数个数 echo "all params : $@" #“$@”会显示所有传给函数的参数 echo "/$1: $1" echo "/$2: $2" echo "/$3: $3" echo "/$4: $4" echo "/$5: $5" echo "/$6: $6" echo "/$7: $7" echo "/$8: $8" echo "/$9: $9" echo "/$0: $0" } myfunc `grep china file.txt`

该shell的执行结果:

-bash-3.00$ ./funcTest.sh params length: 9 all params : chen china engineer lee china leader lynn china programmer $1: chen $2: china $3: engineer $4: lee $5: china $6: leader $7: lynn $8: china $9: programmer $0: ./funcTest.sh

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

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

 

第二种方式:

使用awk:

 

例:

myfunc2 () { awk '{ printf("$1:%s/n", $1) printf("$2:%s/n", $2) printf("$3:%s/n", $3) printf("$0:%s/n", $0) printf("-----------/n") }' } grep china file.txt|myfunc2

执行结果:

$1:chen $2:china $3:engineer $0:chen china engineer ----------- $1:lee $2:china $3:leader $0:lee china leader ----------- $1:lynn $2:china $3:programmer $0:lynn china programmer

可以看到,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.

你可能感兴趣的:(bash:如何给function传参数)