Bash
在 bash 中使用 getopts 處理可選參數
我有一個 bash 腳本,它處理帶有可選參數的輸入文件。腳本看起來像這樣
#!/bin/bash while getopts a:b:i: option do case "${option}" in a) arg1=${OPTARG};; b) arg2=${OPTARG};; i) file=${OPTARG};; esac done [ -z "$file" ] && { echo "No input file specified" ; exit; } carry out some stuff
腳本執行良好,但我需要像這樣指定輸入文件
sh script.sh -a arg1 -b arg2 -i filename
我希望能夠在沒有
-i
選項的情況下呼叫腳本,就像這樣sh script.sh -a arg1 -b arg2 filename
當沒有指定輸入文件時仍然有錯誤消息。有沒有辦法做到這一點?
#!/bin/sh - # Beware variables can be inherited from the environment. So # it's important to start with a clean slate if you're going to # dereference variables while not being guaranteed that they'll # be assigned to: unset -v file arg1 arg2 # no need to initialise OPTIND here as it's the first and only # use of getopts in this script and sh should already guarantee it's # initialised. while getopts a:b:i: option do case "${option}" in (a) arg1=${OPTARG};; (b) arg2=${OPTARG};; (i) file=${OPTARG};; (*) exit 1;; esac done shift "$((OPTIND - 1))" # now "$@" contains the rest of the arguments if [ -z "${file+set}" ]; then if [ "$#" -eq 0 ]; then echo >&2 "No input file specified" exit 1 else file=$1 # first non-option argument shift fi fi if [ "$#" -gt 0 ]; then echo There are more arguments: printf ' - "%s"\n' "$@" fi
我將其更改為
bash
,因為該程式碼中sh
沒有任何特定內容。bash