在 Bash 指令碼中使用 getopts

  1. 在 Bash getopts 中使用引數解析選項
  2. 在 Bash getopts 中解析不帶引數的選項
在 Bash 指令碼中使用 getopts

本教程通過解析帶引數的選項和不帶引數的選項來展示 bash 指令碼中 getopts 的用法。

在 Bash getopts 中使用引數解析選項

字母 nc 前面都有:。這意味著我們希望在使用選項 -n-c 時提供一個引數。變數 opt 儲存了由 getopts 解析的當前選項的值。

while getopts n:c: opt do  case "${opt}" in  n) name=${OPTARG};;  c) country=${OPTARG}  esac done echo "I am $name"; echo "And I live in $country"; 

當我們執行指令碼時,-n 選項提供 John 作為引數,而 -c 選項提供 Britain 作為引數。

bash flags.sh -n John -c Britain 

輸出:

I am John And I live in Britain 

在 Bash getopts 中解析不帶引數的選項

這將使用一個簡單的 bash 指令碼,它在傳遞 -h 選項時列印指令碼 usage,並在使用 -p 選項和指定的資料夾路徑時列印資料夾的內容作為爭論。

第一個 : 表示 getopts 不會報告任何錯誤。相反,我們將自己處理錯誤。字母 p 前面有一個 :,而字母 h 沒有。這意味著無論何時使用 -p 選項,我們都需要一個引數,但 -h 選項可以不帶引數使用。

-h 選項被傳遞時,它會呼叫 usage 函式。-p 選項分配傳遞給 path 變數的引數,然後將其作為引數傳遞給 list 函式。* 指定每當傳遞一個不是 -h-p 的選項時要採取的操作。

#!/bin/bash  function usage {  printf "Usage:\n"  printf " -h Display this help message.\n"  printf " -p <folder path> List contents of specified folder.\n"  exit 0 }  function list {  ls -l $1 }  while getopts :p:h opt; do  case ${opt} in  h)  usage  ;;  p) path=${OPTARG}  list $path  #echo $folder  ;;  *)  printf "Invalid Option: $1.\n"  usage  ;;  esac done 

使用 -h 選項執行指令碼:

 ./getopts.sh -h Usage:  -h Display this help message.  -p <folder path> List contents of specified folder. 

使用 -p 選項執行指令碼:

./getopts.sh -p /home/fumba/example total 0 -rw-r--r-- 1 fumba fumba 0 Nov 1 21:43 file1.txt -rw-r--r-- 1 fumba fumba 0 Nov 1 21:43 file2.txt drwxr-xr-x 1 fumba fumba 4096 Nov 1 21:43 pictures 

使用無效選項 -k 執行指令碼:

./getopts.sh -k Invalid Option: -k. Usage:  -h Display this help message.  -p <folder path> List contents of specified folder. 
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Fumbani Banda
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub

相關文章 - Bash Script