我想在 bash (?:) 中執行三元運算,如果變數為空,則提供默認值。
#!/bin/bash
while getopts l:m:ch:eh:cate:op:b flag
do
case "${flag}" in
l) localities=${OPTARG};;
m) mode=${OPTARG};;
ch) cbhost=${OPTARG};;
eh) eshost=${OPTARG};;
cate) category=${OPTARG};;
op) outputDir=${OPTARG};;
b) s3bucket=${OPTARG};;
esac
done
在所有變數中,cbhost 和 eshost 是可選變數。如何在 bash 中檢查是否為 null,然后使用三元運算分配默認值?或者如何為每個變數分配默認值,如果傳遞引數,這些變數可以被覆寫。
提前致謝。
uj5u.com熱心網友回復:
按照man getopt
Optstring是一串可識別的選項字母(參見 getopt(3));如果一個字母后跟一個冒號,則該選項應該有一個引數,該引數可能會或可能不會被空格分隔。
所以有幾個問題:
- 您不能使用多字母字串作為選項。它只能是單個字母
- 似乎您期望選項的選項值,
-b但沒有使用尾隨: - 您可以在單個 for 回圈中設定每個變數的默認值,如下所示。
這是建議的代碼:
#!/bin/bash
# set default value for these variables
declare localities='loc123' mode='m123' category='cat123' \
outputDir='op123' s3bucket='s3123' cbhost='https://cbhost:1091/'
while getopts l:m:c:e:y:d:b: flag
do
case "${flag}" in
l) localities=${OPTARG};;
m) mode=${OPTARG};;
c) cbhost=${OPTARG};;
e) eshost=${OPTARG};;
y) category=${OPTARG};;
d) outputDir=${OPTARG};;
b) s3bucket=${OPTARG};;
esac
done
# check values of your variables
declare -p localities mode category outputDir s3bucket cbhost eshost
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/517847.html
標籤:重击壳Unix
