如何編寫一個帶有可選輸入參數的bash腳本?

本文翻譯自: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 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章