说,我在bashrc别名中有一个命令,可能需要变量参数/参数。我可以使用if else编写它,如下所示
yd(){
if (( $# )) && (( $1 == 1 ));
then
youtube-dl -f 18 "$2" && aplay /usr/share/sounds/ubuntu/stereo/message.ogg && notify-send 'Youtube Download Completed !'
fi
if (( $# )) && (( $1 == 2 ));
then
youtube-dl -f "$2" "$3" && aplay /usr/share/sounds/ubuntu/stereo/message.ogg && notify-send 'Youtube Download Completed !'
fi
}
其中1st参数表示我需要的参数数量。我想知道是否有办法将可变数量的参数发送到别名
答案 0 :(得分:0)
你不需要做任何特别的事情。 shell函数没有预期的参数数量;您只需访问$1
,$2
等所提供的内容即可。您可以将该函数编写为
yd () {
if (( $# == 0 )); then
printf 'Need at least 1 argument\n' >&2
return 1
fi
arg1=18
arg2=$1
if (( $# > 1 )); then
arg1=$1
arg2=$2
fi
youtube-dl -f "$arg1" "$arg2" &&
aplay /usr/share/sounds/ubuntu/stereo/message.ogg &&
notify-send 'Youtube Download Completed !'
}
但是,反转函数参数的顺序可能更有意义;那么你可以简单地为第二个提供默认值18,如果它没有给出。
# yd foo runs youtube-dl 18 foo
# yd foo 9 runs youtube-dl 9 foo
yd () {
# Return 1 and print an error message if no first argument
arg2=${1:?First argument required}
# Use 18 if no second argument
arg1=${2:-18}
youtube-dl -f "$arg1" "$arg2" &&
aplay /usr/share/sounds/ubuntu/stereo/message.ogg &&
notify-send 'Youtube Download Completed !'
}
在任何一种情况下,如果使用超过2个参数调用yd
,谁在乎呢? yd
只是忽略$3
,$4
等