shell腳本傳可選參數 getopts 和 getopt的方法

寫了一個shell腳本,需要向shell腳本中傳參數供腳本使用,達到的效果是傳的參數可以是可選參數

下面是一個常規化的shell腳本:

        echo "執行的文件名為: $0";echo "第一個參數名為: $1";echo "第二個參數名為: $2"

正常的向shell腳本中傳參數的方法為:

             ./test.sh 1 2 3

最后執行的結果為:

?

        執行的文件名為: ./test.sh第一個參數名為: 1第二個參數名為: 2

但是這個是只能按照順序傳遞參數,并且不能傳遞可選參數,然后查資料,發現了一個shell的getopts 用法

?首先貼個例子

復制代碼
[hello@Git shell]$ bash test.sh -a hello
this is -a the arg is ! hello
[hello@Git shell]$ more test.sh 
#!/bin/bashwhile getopts "a:" opt; docase $opt ina)echo "this is -a the arg is ! $OPTARG" ;;\?)echo "Invalid option: -$OPTARG" ;;esac
done
復制代碼

getopts一共有兩個參數,第一個是-a這樣的選項,第二個參數是 hello這樣的參數。

選項之間可以通過冒號:進行分隔,也可以直接相連接,:表示選項后面必須帶有參數,如果沒有可以不加實際值進行傳遞

例如:getopts ahfvc: option表明選項a、h、f、v可以不加實際值進行傳遞,而選項c必須取值。使用選項取值時,必須使用變量OPTARG保存該值。

復制代碼
[hello@Git shell]$ bash test.sh -a hello -b
this is -a the arg is ! hello
test.sh: option requires an argument -- b
Invalid option: -
[hello@Git shell]$ bash test.sh -a hello -b hello -c 
this is -a the arg is ! hello
this is -b the arg is ! hello
this is -c the arg is ! 
[hello@Git shell]$ more test.sh 
#!/bin/bashwhile getopts "a:b:cdef" opt; docase $opt ina)echo "this is -a the arg is ! $OPTARG" ;;b)echo "this is -b the arg is ! $OPTARG" ;;c)echo "this is -c the arg is ! $OPTARG" ;;\?)echo "Invalid option: -$OPTARG" ;;esac
done
[hello@Git shell]$ 
復制代碼

執行結果結合代碼顯而易見。同樣你也會看到有些代碼在a的前面也會有冒號,比如下面的

情況一,沒有冒號:

復制代碼
[hello@Git shell]$ bash test.sh -a hello
this is -a the arg is ! hello
[hello@Git shell]$ bash test.sh -a
test.sh: option requires an argument -- a
Invalid option: -
[hello@Git shell]$ more test.sh 
#!/bin/bashwhile getopts "a:" opt; docase $opt ina)echo "this is -a the arg is ! $OPTARG" ;;\?)echo "Invalid option: -$OPTARG" ;;esac
done
[hello@Git shell]$ 
復制代碼

情況二,有冒號:

復制代碼
[hello@Git shell]$ bash test.sh -a hello
this is -a the arg is ! hello
[hello@Git shell]$ bash test.sh -a 
[hello@Git shell]$ more test.sh 
#!/bin/bashwhile getopts ":a:" opt; docase $opt ina)echo "this is -a the arg is ! $OPTARG" ;;\?)echo "Invalid option: -$OPTARG" ;;esac
done
復制代碼

情況一輸入 -a 但是后面沒有參數的的時候,會報錯誤,但是如果像情況二那樣就不會報錯誤了,會被忽略。

while getopts ":a:bc" opt? #第一個冒號表示忽略錯誤;字符后面的冒號表示該選項必須有自己的參數?

參考?https://blog.csdn.net/xluren/article/details/17489667

但是這樣還是無法滿足可以輸入可選參數的要求,這樣輸入的參數名稱也是固定的,參數的數量也是固定的,然后接下來了解了shell 的getopt用法。

看過官方文檔后,自己寫了個小demo

復制代碼
#!/bin/bash#獲取對應的參數 沒有的話賦默認值
ARGS=`getopt -o a::b::l::n::t::p:: --long along::,blong::,llong::,plong:: -n 'example.sh' -- "$@"`
if [ $? != 0 ]; thenecho "Terminating..."exit 1
fi#echo $ARGS
#將規范化后的命令行參數分配至位置參數($1,$2,...)
eval set -- "${ARGS}"while true;
docase "$1" in-a|--along)case "$2" in"")project1_name=master;shift 2;;;*)project1_name=$2;shift 2;;;esac;;-b|--blong)case "$2" in"")project2_name=master;shift 2;;*)project2_name=$2;shift 2;;;esac;;-l|--llong)case "$2" in"")layer=layer_1;shift 2;;*)layer=$2;shift 2;;;esac;;-n)case "$2" in"")number=1000;shift 2;;*)number=$2;shift 2;;;esac;;-t)case "$2" in"")select_type=top;shift 2;;*)select_type=$2;shift 2;;;esac;;-p)case "$2" in"")data_point=;shift 2;;*)data_point=$2;shift 2;;;esac;;--)shiftbreak;;*)echo "Internal error!"exit 1;;esacdoneproject1_name=${project1_name:-master}
project2_name=${project2_name:-master}
layer=${layer:-layer_1}
number=${number:-100}
select_type=${select_type:-top}
data_point=${data_point:-}
復制代碼

這一部分為輸入參數對應的字符

a::b::l::n::t::p::

?

#-o表示短選項,兩個冒號表示該選項有一個可選參數,可選參數必須緊貼選項,如-carg 而不能是-c arg

#--long表示長選項

一目了然,首先是根據傳遞過來的 是 -a? 還是 -b? -l 進行判斷,如果只有-a后面沒有參數的話 則賦默認值,同時在

project1_name=${project1_name:-master}
project2_name=${project2_name:-master}
layer=${layer:-layer_1}
number=${number:-100}
select_type=${select_type:-top}
data_point=${data_point:-}

這一步 也進行了默認值的賦值操作。如果上面沒有 project1_name? 則賦值為master

例子如下:

復制代碼
參數的默認值設置$cat myscript.shprint ${1:-hello}print ${2:-kshell}$sh myscript.shhellokshell
復制代碼

?

轉載于:https://www.cnblogs.com/linwenbin/p/10800756.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/277809.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/277809.shtml
英文地址,請注明出處:http://en.pswp.cn/news/277809.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Teams Tab App 代碼深入淺出 - 配置頁面

上一篇文章我們使用Teams Toolkit 來創建、運行 tab app。這篇文章我們深入來分析看一下tab app 的代碼。 先打開代碼目錄,可以看到在 src 目錄下有入口文件 index.tsx,然后在 components 目錄下有更多的一些 tsx 文件,tsx 是 typescript的一…

labelme標注的json文件數據轉成coco數據集格式(可處理目標框和實例分割)

這里主要是搬運一下能找到的 labelme標注的json文件數據轉成coco數據集格式(可處理目標框和實例分割)的代碼,以供需要時參考和提供相關幫助。 1、官方labelme實現 如下是labelme官方網址,提供了源代碼,以及相關使用方…

EpSON TM-82II驅動在POS系統上面安裝問題處理

按照品牌名稱,在網上下載的安裝包為apstmt82.rar 下面講解一下,如何的解決愛普生打印機在POS機器上面的安裝問題,這個算是一個比較奇特的故障問題,不像其它的新北冰洋(SN3C)的U80_U80II,SeNor的…

打印圖片的屬性和實現另存圖片功能以及使用numpy

上一篇我們已經學了如何讀取圖片的功能了以及和opencv的環境搭建了,今天接著來學習,哈哈哈,今天剛好五一,也沒閑著,繼續學習。 1、 首先我們來實現打印出圖片的一些屬性功能, 先來看一段代碼: 1…

Ubuntu 18.04下命令安裝VMware Tools

2019獨角獸企業重金招聘Python工程師標準>>> sudo apt-get upgrade sudo apt-get install open-vm-tools-desktop -y sudo reboot 轉載于:https://my.oschina.net/u/574036/blog/1829455

phpstorm PHP language level無法選擇

phpstorm PHP7新特性一直提示紅色波浪線,應該是沒有設置PHP 版本,但是打開PHPstorm---preference--lannguage&frameworks--PHP , 發現PHP language level 無法選擇PHP7.2 ,查看旁邊的提示信息說是同步了composer 的原因&#…

Qfile

打開方式: 1 void AddStudents::write_to_file(QString src){2 QFile file("stu.txt");3 if (!file.open(QIODevice::Append | QIODevice::Text)){4 QMessageBox::critical(this,"打開文件錯誤","確認");5 r…

多層裝飾器、帶參數裝飾器

# 帶參數的裝飾器 # import time # FLAGE False # 加個標志位,使全部的裝飾器可以失效或有效 # def timmer_out(flag): # def timmer(func): # def inner(*args,**kwargs): # if flag: # start time.time() # …

IDEA svn 菜單不見了,解決方法

2019獨角獸企業重金招聘Python工程師標準>>> 參考地址: http://www.cnblogs.com/signheart/p/193448a98f92bd0cc064dbd772dd9f48.html,我是第二種方法解決的! 轉載于:https://my.oschina.net/liuchangng/blog/1829679

蘇寧易購:Hadoop失寵前提是出現更強替代品

在筆者持續調研國內Hadoop生態系統生存現狀的同時,KDnuggets發布的2018年數據科學和機器學習工具調查報告再次將“Hadoop失寵”言論復活。報告一出,“Hadoop被拋棄”幾個字瞬時成為各大標題黨的最愛,充斥在不同的新聞平臺。這些報告和數據是否…

VS2017生成一個簡單的DLL文件 和 LIB文件——C語言

下面我們將用兩種不同的姿勢來用VS2017生成dll文件(動態庫文件)和lib文件(靜態庫文件),這里以C語言為例,用最簡單的例子,來讓讀者了解如何生成dll文件(動態庫文件) 生成動…

Hive數據類型及文本文件數據編碼

本文參考Apache官網,更多內容請參考:https://cwiki.apache.org/confluence/display/Hive/LanguageManualTypes 1. 數值型 類型支持范圍TINYINT1-byte signed integer, from -128 to 127SMALLINT2-byte signed integer, from -32,768 to 32,767INT/INTEGE…

Python繪圖Turtle庫詳解

轉載:https://blog.csdn.net/zengxiantao1994/article/details/76588580 Turtle庫是Python語言中一個很流行的繪制圖像的函數庫,想象一個小烏龜,在一個橫軸為x、縱軸為y的坐標系原點,(0,0)位置開始,它根據一組函數指令…

(待完成)qbxt2019.05 總結2 - 數位DP

數位 DP 嚴格來說其實并不是 DP……它只是個單純的計數問題 但是怎么說呢……現在大家似乎都把數位 DP 叫這個名字,所以……我們還是……叫它 DP 額什么是數位 DP 呢? 一句話概括——一類求在 K 進制下m滿足條件的數的數量有多少個的算法 常見的問題形式…

mac使用brew update無反應解決辦法

為什么80%的碼農都做不了架構師?>>> mac系統中使用brew作為包管理工具,類似centos中的yum,ubuntu中的apt-get,在使用brew update的使用,有時候會長時間無反應,或者中途斷開連接,這是…

2018-2019-2 20175223 實驗三《敏捷開發與XP實踐》實驗報告

目錄 北京電子科技學院(BESTI)實驗報告實驗名稱:實驗三 敏捷開發與XP實踐實驗內容、步驟與體會:一、實驗三 敏捷開發與XP實踐-1二、實驗三 敏捷開發與XP實踐-2三、實驗三 敏捷開發與XP實踐-3四、實驗三 敏捷開發與XP實踐-4五、代碼…

(八)路徑(面包屑導航)分頁標簽和徽章組件

一&#xff0e;路徑組件 路徑組件也叫做面包屑導航。 <ol class"breadcrumb"><li><a href"#">首頁</a></li><li><a href"#">產品列表</a></li><li><a href"#">大…

第十周總結

失望光年轉載于:https://www.cnblogs.com/daisy99lijing/p/11064924.html

LC #45 JS

效率低下 最起碼容易看得懂&#xff1f;將就看吧 /*** param {number[]} nums* return {number}*/ var jump function(nums) {let len nums.length;if(len < 1){return 0;}function calPossibleLastStep(index){let res [];if(index > len){return res;}if(index <…

python之爬蟲(四)之 Requests庫的基本使用

什么是Requests Requests是用python語言基于urllib編寫的&#xff0c;采用的是Apache2 Licensed開源協議的HTTP庫如果你看過上篇文章關于urllib庫的使用&#xff0c;你會發現&#xff0c;其實urllib還是非常不方便的&#xff0c;而Requests它會比urllib更加方便&#xff0c;可以…