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

本文介绍了如何在bash脚本中添加可选输入参数。通过设置默认值和利用变量替换,可以实现参数的灵活性。文章提供了一些示例,包括处理带有空格的文件路径的问题,并展示了一种方法,允许脚本接受日期作为可选参数。
摘要由CSDN通过智能技术生成

本文翻译自: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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值