我希望我的脚本能够接受一个可选的输入,

目前我的剧本是

#!/bin/bash
somecommand foo

但我想说:

#!/bin/bash
somecommand  [ if $1 exists, $1, else, foo ]

当前回答

可以使用变量替换将固定值或命令(如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

其他回答

可以使用变量替换将固定值或命令(如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

对于可选的多个参数,类似于ls命令,它可以接受一个或多个文件,或默认列出当前目录中的所有内容:

if [ $# -ge 1 ]
then
    files="$@"
else
    files=*
fi
for f in $files
do
    echo "found $f"
done

对于路径中有空格的文件不能正确工作,唉。还不知道该怎么做。

请不要忘记,如果它是变量$1 ..$ n 您需要写入一个常规变量来使用替换

#!/bin/bash
NOW=$1
echo  ${NOW:-$(date +"%Y-%m-%d")}

你可以像这样为一个变量设置一个默认值:

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