我希望我的脚本能够接受一个可选的输入,
目前我的剧本是
#!/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.sh
#!/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
其他回答
可以使用变量替换将固定值或命令(如date)替换为参数。到目前为止,答案都集中在固定值上,但这是我用来使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
if [ ! -z $1 ]
then
: # $1 was given
else
: # $1 was not given
fi
你可以像这样为一个变量设置一个默认值:
somecommand.sh
#!/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
请不要忘记,如果它是变量$1 ..$ n 您需要写入一个常规变量来使用替换
#!/bin/bash
NOW=$1
echo ${NOW:-$(date +"%Y-%m-%d")}
这允许为可选的第一个参数设置默认值,并保留多个参数。
> cat mosh.sh
set -- ${1:-xyz} ${@:2:$#} ; echo $*
> mosh.sh
xyz
> mosh.sh 1 2 3
1 2 3