bash参数解析函数

Hei*_*ich 3 bash arguments function

解析函数中的bash脚本参数是一种解决方法

run命令:./ script.sh -t -r -e

脚本:

#!/bin/sh
# parse argument function
parse_args() {
echo "$#"   #<-- output: 0
}


# main
echo "$#"   #<-- output: 3

# parsing arguments
parse_args
Run Code Online (Sandbox Code Playgroud)

Dav*_*ter 9

$#计算当前范围中的参数数量.由于每个函数都有自己的作用域,并且您没有传递任何参数parse_args,$#因此它内部始终为0.

要获得所需结果,请将最后一行更改为:

parse_args "$@"
Run Code Online (Sandbox Code Playgroud)

特殊变量"$@"扩展为当前(顶级)范围的位置参数,作为单独的单词.随后他们被传递给了parse_args.