预期结果不会在shell脚本中返回

时间:2014-02-12 02:38:42

标签: shell

我在shell脚本中编写了以下代码:

#!/bin/bash
tput clear
a=$(date +"%k")
if [ $a -lt 12 ]
then
echo "Hi!Good Morning"
fi
if [ $a -ge 12 -a $a -le 17 ]
then
echo "Hi!Good Afternoon"
fi
if [ $a -gt 17 -a $a -le 19 ]
then
echo "Hi!Good Evening"
fi
if [ $a -gt 19 -a $a -le 24 ]
then
echo "Hi!Good Night"
fi
while [ : ]
do

    echo "BCSE!!\c" 
    read comm
    set comm
    case "$1" in
        [""])
            continue
        ;;
    esac
    case "$1" in
        ["editme"])
            xdg-open "$2"& 
        ;;
    esac
        case "$1" in
        ["newd"])
            mkdir -p "$2"
        ;;
    esac
    case "$1" in
        ["mycontent"])
            if [ -f "$2" ]
            then
                xdg-open "$2"&
            else
                echo "File doesn't exist"
            fi
        ;;
    esac
    case "$1" in
        ["exitbcse"])
                break
        ;;
    esac
    case "$1" in
        [*])
            echo "Wrong command!!";;
    esac
done

输出应为:

Hi!Good morning
BCSE!!editme filename 

现在文件没有打开而是我

Hi!Good morning
BCSE!!editme filename
BCSE!!

1 个答案:

答案 0 :(得分:1)

而不是:

while [ : ]

您可能想写:

while :

while true

while [ : ]可能有效,但不是因为正确的原因,该句子运行命令[,命令[检查你在里面写的表达式,因为它是非空的string返回一个真值(零),为了说明这一点,如果你运行while [ false ],你也会得到一个无限循环。

case控制结构中,必须在没有[]""的情况下编写选项。     案例“$ 1”in         exitbcse)                 打破         ;;     ESAC

修改

使用我上面描述的更正以及其他修正来检查此示例:

#!/bin/bash
tput clear
a=$(date +"%k")
if [ $a -lt 12 ]
then
    echo "Hi!Good Morning"
elif [ $a -ge 12 -a $a -le 17 ]
then
    echo "Hi!Good Afternoon"
elif [ $a -gt 17 -a $a -le 19 ]
then
    echo "Hi!Good Evening"
elif [ $a -gt 19 -a $a -le 24 ]
then
    echo "Hi!Good Night"
fi
while true
do
    echo "BCSE!!\c" 
    read comm option
    case "$comm" in
        "")
            continue
            ;;
        "editme")
            xdg-open "$option"& 
            ;;
        "newd")
            mkdir -p "$option"
            ;;
        "mycontent")
            if [ -f "$option" ]
            then
                xdg-open "$option"&
            else
                echo "File doesn't exist"
            fi
            ;;
        "exitbcse")
            break
            ;;
        *)
            echo "Wrong command!!";;
    esac
done