如何编写一个采用可选输入参数的bash脚本?

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

例如,目前我的脚本是

#!/bin/bash
somecommand foo

但我希望它说:

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

你可以使用默认值语法:

somecommand ${1:-foo}

以上将如Bash参考手册 - 3.5.3 Shell参数扩展[我的重点]中所述:

如果参数未设置或为空,则替换单词的扩展。 否则,参数的值将被替换。

如果您只想在参数未设置的情况下替换默认值(但不是如果它为空,例如不是如果它是空字符串),请使用以下语法:

somecommand ${1-foo}

再次从Bash参考手册 - 3.5.3外壳参数扩展:

省略冒号只会导致未设置参数的测试。 换句话说,如果包含冒号,则运算符会测试两个参数的存在并且它的值不为空; 如果省略冒号,则操作员仅测试存在。


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

somecommand.sh

#!/usr/bin/env bash

ARG1=${1:-foo}
ARG2=${2:-bar}
ARG3=${3:-1}
ARG4=${4:-$(date)}

echo "$ARG1"
echo "$ARG2"
echo "$ARG3"
echo "$ARG4"

以下是一些如何工作的例子:

$ ./somecommand.sh
foo
bar
1
Thu Mar 29 10:03:20 ADT 2018

$ ./somecommand.sh ez
ez
bar
1
Thu Mar 29 10:03:40 ADT 2018

$ ./somecommand.sh able was i
able
was
i
Thu Mar 29 10:03:54 ADT 2018

$ ./somecommand.sh "able was i"
able was i
bar
1
Thu Mar 29 10:04:01 ADT 2018

$ ./somecommand.sh "able was i" super
able was i
super
1
Thu Mar 29 10:04:10 ADT 2018

$ ./somecommand.sh "" "super duper"
foo
super duper
1
Thu Mar 29 10:05:04 ADT 2018

$ ./somecommand.sh "" "super duper" hi you
foo
super duper
hi
you

if [ ! -z $1 ] 
then 
    : # $1 was given
else
    : # $1 was not given
fi
链接地址: http://www.djcxy.com/p/42699.html

上一篇: How to write a bash script that takes optional input arguments?

下一篇: PHP in python through bash