如果留空,我如何跳回到先前的读数

时间:2014-08-13 13:49:31

标签: bash

Default_Dir=/export/home/cwatts/test
Default_Log=DB.Audit

echo "Please, enter your Fullname [ENTER]:"
read fname

if [ -z "$fname" ]; then
    echo "Please enter a value!"
    exit 0
else
    echo "Please, enter the Database name [ENTER]:"
    read dbname
    if [ -z "$dbname" ]; then
        echo "Please enter a value!"
    else
        echo "Please, enter a brief Description [ENTER]:"
        read desc
        if [ -z "$desc" ]; then
            echo "Please enter a value!"
        fi
    fi
fi

if [ ! -d $Default_Dir ]; then
    echo "directory doesn't exit, it will be created"
    mkdir $Default_Dir
fi

echo `date -u` $dbname $fname $desc >> $Default_Dir/$Default_Log
exit

2 个答案:

答案 0 :(得分:1)

您可以这样做:

while [ -z "${value-}" ]
do
    echo "Please, enter your Fullname [ENTER]:"
    read value
done

答案 1 :(得分:0)

在l0b0的答案上进行了一些扩展并重构了易读性和惯用语:

nonempty () {
    test -n "$1" && return 0
    echo "Please enter a value" >&2
    return 1
}

while true; do
    read -p "Please, enter your Fullname [ENTER]: " fname
    nonempty "$fname" || continue
    read -p "Please, enter the Database name [ENTER]: " dbname
    nonempty "$dbname" || continue
    read -p "Please, enter a brief Description [ENTER]:" desc
    nonempty "$desc" || continue
    break
done

date -u +"%c $dbname $fname $desc" >> $Default_Dir/$Default_Log

(如果任何值都包含百分号,那么将要以#{1}}格式字符串回显的字符串放入的hack将会中断。)

如果您对使用函数为您定义全局变量的稍微可疑的做法感到满意,则代码重复仍然可以显着减少。

date

间接变量引用accept () { read -p "$2 [ENTER]: " "$1" test -n "${!1}" && return 0 echo "Please enter a value" >&2 return 1 } while true; do accept fname "Please, enter your Fullname" || continue accept dbname "Please, enter the Database name" || continue accept desc "Please, enter a brief Description" || continue break done 是一种Bashism,不能移植到其他shell。