在BASH中捕获错误并要求手动输入

时间:2014-10-24 17:09:52

标签: linux bash shell

我有以下代码:

if [ -e /etc/my.cnf ]; then
    _out_fn="/etc/my.cnf"
        if [ ! -e ${_out_fn}_orig ] ; then
        cp $_out_fn ${_out_fn}_orig
        fi
    cp /dev/null $_out_fn
    while read line ; do
    set -- $line
        if [ "$1" = "[mysqld]" ] ; then
            echo $line >> $_out_fn
            line="safe-show-database
            skip-networking
            local-infile=0
            symbolic-links=0"
        fi
    echo $line >> $_out_fn
    done < ${_out_fn}_orig
    echo "$MySQL Securing Complete! "
else
    echo "$MySQL Configuration File Not Found! "
fi

有没有办法让代码在发生故障时要求手动定位?

1 个答案:

答案 0 :(得分:1)

使用read。要求手动输入的代码段如下所示:

config_location=
while : ; do
        echo -n "Enter the path to the configuration file: "
        read config_location
        if test -r "$config_location"; then
                break
        fi
        echo "File $config_location not found or is unreadable, let's try again."
done
echo "OK, $config_location exists."

这里我们继续询问用户,直到他提供的路径存在且可读(test -r)。 while : ; do是一个无限循环。如果您只需要询问一次路径,则只需要:

echo -n "Enter the path to the configuration file: "
read config_location