我希望我的脚本能够接受一个可选的输入参数,
例如,当前我的脚本是这样的:
#!/bin/bash
somecommand foo
但我希望它说:
#!/bin/bash
somecommand [ if $1 exists, $1, else, foo ]
我希望我的脚本能够接受一个可选的输入参数,
例如,当前我的脚本是这样的:
#!/bin/bash
somecommand foo
但我希望它说:
#!/bin/bash
somecommand [ if $1 exists, $1, else, foo ]
somecommand ${1:-foo}
somecommand ${1-foo}
省略冒号只会检测未设置的参数。换句话说,如果包含了冒号,该运算符测试参数的存在性和其值不为空;如果省略了冒号,则该运算符仅测试参数的存在性。
$1
未设置或为空字符串,则返回foo
" 和 ${1-foo}
之间的语义差异,"${1-foo}" 的意思是 "如果 $1
未设置,则返回 foo
"。 - l0b0您可以这样为变量设置默认值:
#!/usr/bin/env bash
ARG1=${1:-foo}
ARG2=${2:-'bar is'}
ARG3=${3:-1}
ARG4=${4:-$(date)}
echo "$ARG1"
echo "$ARG2"
echo "$ARG3"
echo "$ARG4"
以下是一些示例,演示如何运作:
$ ./somecommand.sh
foo
bar is
1
Thu 19 May 2022 06:58:52 ADT
$ ./somecommand.sh ez
ez
bar is
1
Thu 19 May 2022 06:58:52 ADT
$ ./somecommand.sh able was i
able
was
i
Thu 19 May 2022 06:58:52 ADT
$ ./somecommand.sh "able was i"
able was i
bar is
1
Thu 19 May 2022 06:58:52 ADT
$ ./somecommand.sh "able was i" super
able was i
super
1
Thu 19 May 2022 06:58:52 ADT
$ ./somecommand.sh "" "super duper"
foo
super duper
1
Thu 19 May 2022 06:58:52 ADT
$ ./somecommand.sh "" "super duper" hi you
foo
super duper
hi
you
if [ ! -z $1 ]
then
: # $1 was given
else
: # $1 was not given
fi
-n
和! -z
是相同的意思。 - l0b0[ -n $1 ]
将始终为真。如果您使用的是bash,则[[ -n $1 ]]
会按预期执行,否则您必须引用 [ -n "$1" ]
。 - glenn jackman你可以用 $#
来检查参数数量。
#!/bin/bash
if [ $# -ge 1 ]
then
$1
else
foo
fi
请不要忘记,如果它是变量 $1 .. $n,您需要将其写入常规变量以使用替换。
#!/bin/bash
NOW=$1
echo ${NOW:-$(date +"%Y-%m-%d")}
DAY=${1:-$(date +%F -d "yesterday")}
。 - Garren S > cat mosh.sh
set -- ${1:-xyz} ${@:2:$#} ; echo $*
> mosh.sh
xyz
> mosh.sh 1 2 3
1 2 3
对于可选的多个参数,类比于可以接受一个或多个文件或默认列出当前目录中所有内容的ls
命令:
if [ $# -ge 1 ]
then
files="$@"
else
files=*
fi
for f in $files
do
echo "found $f"
done
遗憾的是,对于路径中带有空格的文件,它不能正常工作。我还没有想出如何让它正常工作。
我们可以使用变量替换来将一个固定值或命令(例如date
)替换为一个参数。迄今为止,答案都集中在固定值上,但这是我用来使日期成为可选参数的方法:
~$ sh co.sh
2017-01-05
~$ sh co.sh 2017-01-04
2017-01-04
~$ cat co.sh
DAY=${1:-$(date +%F -d "yesterday")}
echo $DAY
while getopts a: flag
do
case "$flag" in
a) arg1=${OPTARG};;
esac
done
echo "Print optional argument: $arg1"
if [[ -z "$arg1" ]]; then
ARG=DEFAULT_VAL
else
ARG=$arg1
fi
#Run using below command (eg: file name : runscript.sh)
bash runscript.sh -a argument_val &
当你使用 ${1: } 时,你可以捕获传递给函数的第一个参数(1),或者(:)你可以捕获一个空格作为默认值。
例如,为了能够使用 Laravel artisan,我将以下内容放入我的 .bash_aliases 文件中:
artisan() {
docker exec -it **container_name** php artisan ${1: } ${2: } ${3: } ${4: } ${5: } ${6: } ${7: }
}
现在,我只需要在命令行中输入:
因此,在这种情况下,我可以选择传递7个参数。
希望这能帮助到某些人。