簡體   English   中英

getopts沒有將我的選項發送到標准輸出

[英]getopts is not sending my options to standard out

我開始嘗試使用getopts,但遇到一些錯誤。 當我輸入無效的選項(例如-A)時,程序輸出不是必需的。

#!/bin/bash

function usage() {
    echo "Usage: $0 -h [database host] -d [test database name]"
    exit 1
}

while getopts “:h:d:” opt; do
  case ${opt} in
    h)
      db_host=$OPTARG
      ;;
    d)
      test_db=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" 1>&2
      usage
      exit 1
      ;;
    :)
      echo “Option -$OPTARG requires an argument.” 1>$2
      usage
      exit 1
      ;;
  esac
done
shift $((OPTIND-1))

if [ -z $db_host ] || [ -z $test_db ]; then
    usage
else
    echo "Your host is $db_host and your test database is $test_db."
fi

程序輸出示例:

./opt.sh: illegal option -- A
Invalid option: -
Usage: ./opt.sh -h [database host] -d [test database name]

因此,基本上有兩個問題:

1)我想完全擺脫此第一條錯誤消息。 我想提供自己的錯誤消息。 2)為什么我的腳本沒有產生“無效選項:-A”,而不僅僅是“無效選項:-”

您在getopts的options參數周圍的引號類型錯誤,它們是“彎引號”而不是ASCII雙引號。 結果, :不是選項的第一個字符,因此您不會得到無提示的錯誤報告。

更改為

while getopts ':h:d:' opt; do

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM