函数内可以有 if-else 吗?
我这里有菜单。
请参阅下面的代码。
#!/bin/bash
#Main Menu
function p_enter
{
echo ""
echo -n "Press Enter to continue"
read
clear
}
function df1
{
read var
if [ $var = "1" ]
then
echo "nice"
else
echo "not bad"
fi
}
select=
until [ "$select" = "0" ]; do
echo ""
echo "MAIN MENU"
echo "1 - XML DATA REPORT"
echo "2 - SOON "
echo ""
echo "0 - exit"
echo ""
echo -n "Enter sleection: "
read select
echo ""
case $select in
1 ) df1 ; press_enter ;;
2 ) free ; press_enter ;;
3 ) exit ;;
* ) echo "nvalid entry"; press_enter
esac
done
有什么提示或建议吗?
答案1
是的,shell 函数可以使用 if/else 语句。
#!/bin/bash
function comment_on_val {
local the_reply="$1"
local the_word="$2"
if (( the_reply == 1 )); then
echo "The value is one ($the_word)"
else
echo "The value isn't one ($the_word)"
fi
}
echo "Menu:"
select word in "Yes" "No" "Exit"; do
case "$REPLY" in
3) break ;;
*) comment_on_val "$REPLY" "$word" ;;
esac
done
local
我在函数中使用的唯一原因是为这两个变量提供局部作用域。如果我不这样做,它们将在调用后存在于脚本的主体中comment_on_val
,这在本例中不是有意的。