Jim*_*Jim 10 shell bash shell-script
我有一个函数,它取决于功能发生变化的参数。
我知道我可以做到:
function foo {
PARAM1=$1
PARAM2="$2"
VAR=$3
if[[ -z "$VAR" ]]; then
# code here
else
# other code here
fi
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更合适的 bash 方法。这会奏效,但我不想有类似的东西
foo "x" "y" "blah"
foo "x" "y" "true"
foo "y" "y" "1"
Run Code Online (Sandbox Code Playgroud)
都是等价的。
有没有更适合 Bash 的方法?
您可以为您的函数提供命令行选项。使用不带参数的命令行选项是向 shell 脚本、shell 函数和实用程序提供二进制/布尔值(“on/off”、“true/false”、“enable/disable”)的常用方法。
foo () {
local flag=false
OPTIND=1
while getopts 't' opt; do
case $opt in
t) flag=true ;;
*) echo 'Error in command line parsing' >&2
exit 1
esac
done
shift "$(( OPTIND - 1 ))"
local param1="$1"
local param2="$2"
if "$flag"; then
# do things for "foo -t blah blah"
else
# do things for "foo blah blah"
fi
}
Run Code Online (Sandbox Code Playgroud)
该选项-t
对于用户来说就像一个布尔标志。使用它会flag
在函数内部设置为true
(将其从其默认值更改为false
)。该-t
选项将用作函数的第一个参数。
调用该函数将使用
foo "some value" "some other value"
Run Code Online (Sandbox Code Playgroud)
或者
foo -t "some value" "some other value"
Run Code Online (Sandbox Code Playgroud)
其中后一个调用会将flag
函数中的变量设置为true
.