case 语句中的变量赋值 (bash)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9556517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variable assignment inside a case statement (bash)
提问by hizki
I am trying to parse incoming options in my bash script, and save the values in variables. This is my code:
我正在尝试解析 bash 脚本中的传入选项,并将值保存在变量中。这是我的代码:
#!/bin/bash
while getopts "H:w:c" flag
do
# echo $flag $OPTIND $OPTARG
case $flag in
H) host = "$OPTARG"
;;
w) warning = "$OPTARG"
;;
c) critical = "$OPTARG"
;;
esac
done
However, the statements inside 'case' must be command-line commands, so I can't make the wanted assignment. What is the right way to do this?
但是,'case' 中的语句必须是命令行命令,因此我无法进行所需的分配。这样做的正确方法是什么?
回答by Adam Liss
Remove the spaces around the =operators:
删除=运算符周围的空格:
case "$flag" in
H) host="$OPTARG" ;;
w) warning="$OPTARG" ;;
c) critical="$OPTARG" ;;
esac
回答by l0b0
You also need to change the optstring - The coption needs to be followed by a colon if you want to collect its argument:
您还需要更改 optstring -c如果您想收集其参数,则该选项需要后跟一个冒号:
while getopts "H:w:c:" flag
回答by Bus42
I took a slightly different approach when creating a script to practice if/then/else and case statements. BTW, if you install cowsay;
在创建脚本来练习 if/then/else 和 case 语句时,我采用了稍微不同的方法。顺便说一句,如果你安装了 cowsay;
sudo apt-get install cowsay
and fortune;
和财富;
sudo apt-get install fortune
you can use this script as is and then play around with it to get used to making assignments in case statements or using if/then/else statements.
您可以按原样使用此脚本,然后使用它来习惯在 case 语句中进行赋值或使用 if/then/else 语句。
#!/bin/bash
echo "Choose a character from the following list:"
echo
echo "1) Beavis"
echo "2) Cow Hitting a Bong"
echo "3) Calvin"
echo "4) Daemon"
echo "5) Dragon and Cow"
echo "6) Ghostbusters"
echo "7) Ren"
echo "8) Stimpy"
echo "9) Sodomized Sheep"
echo "0) Mech and Cow"
#
echo
read character
echo
#
case "$character" in
"1") file="beavis.zen.cow" ;;
"2") file="bong.cow" ;;
"3") file="calvin.cow" ;;
"4") file="daemon.cow" ;;
"5") file="dragon-and-cow.cow" ;;
"6") file="ghostbusters.cow" ;;
"7") file="ren.cow" ;;
"8") file="stimpy.cow" ;;
"9") file="sodomized-sheep.cow" ;;
"0") file="mech-and-cow.cow" ;;
*) clear; ./cowsay.sh;
esac
#
#echo "var 'file' == $file"
echo "What would you like your character to say?"
echo "Alternatively, if you want your character to"
echo "read you your fortune, type 'fortune'."
read input_string
#
if [ $input_string = fortune ] ; then
clear; $input_string | cowsay -f /usr/share/cowsay/cows/$file
else
clear; cowsay -f /usr/share/cowsay/cows/$file $input_string
fi
~

