本文翻译自:How to write a bash script that takes optional input arguments?
I want my script to be able to take an optional input, 我希望我的脚本能够获取可选输入,
eg currently my script is 例如,目前我的剧本是
#!/bin/bash
somecommand foo
but I would like it to say: 但我想说:
#!/bin/bash
somecommand [ if $1 exists, $1, else, foo ]
#1楼
参考:https://stackoom.com/question/d9t4/如何编写一个带有可选输入参数的bash脚本
#2楼
please don't forget, if its variable $1 .. $n you need write to a regular variable to use the substitution 请不要忘记,如果它的变量$ 1 .. $ n你需要写一个常规变量来使用替换
#!/bin/bash
NOW=$1
echo ${NOW:-$(date +"%Y-%m-%d")}
#3楼
You can set a default value for a variable like so: 您可以为变量设置默认值,如下所示:
somecommand.sh 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"
Here are some examples of how this works: 以下是一些如何工作的示例:
$ ./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
#4楼
For optional multiple arguments, by analogy with the ls command which can take one or more files or by default lists everything in the current directory: 对于可选的多个参数,可以通过类似于ls命令来获取一个或多个文件,或者默认列出当前目录中的所有内容:
if [ $# -ge 1 ]
then
files="$@"
else
files=*
fi
for f in $files
do
echo "found $f"
done
Does not work correctly for files with spaces in the path, alas. 对于路径中包含空格的文件,它无法正常工作,唉。 Have not figured out how to make that work yet. 还没弄明白如何做到这一点。
#5楼
It's possible to use variable substitution to substitute a fixed value or a command (like date ) for an argument. 可以使用变量替换来替换参数的固定值或命令(如date )。 The answers so far have focused on fixed values, but this is what I used to make date an optional argument: 到目前为止,答案都集中在固定值上,但这是我过去将日期作为可选参数的原因:
~$ 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
#6楼
This allows default value for optional 1st arg, and preserves multiple args. 这允许可选1st arg的默认值,并保留多个args。
> cat mosh.sh
set -- ${1:-xyz} ${@:2:$#} ; echo $*
> mosh.sh
xyz
> mosh.sh 1 2 3
1 2 3
本文介绍了如何在bash脚本中添加可选输入参数。通过设置默认值和利用变量替换,可以实现参数的灵活性。文章提供了一些示例,包括处理带有空格的文件路径的问题,并展示了一种方法,允许脚本接受日期作为可选参数。
2965

被折叠的 条评论
为什么被折叠?



