带有If,Select和Case的Shell脚本

时间:2013-10-01 14:56:30

标签: bash shell unix

任何人都可以建议如何编辑此脚本以执行以下操作:

如果文件夹存在 - “那么您确定要卸载吗?” 如果是 - 执行文件复制,如果没有则停止脚本。 否则 - 找不到文件夹,停止脚本。

if [ -e "/tmp/installpackage" ]
then
    echo "Are you sure you want to uninstall?"
    select yn in "Yes" "No"; do
        case $yn in
            Yes ) 
                echo "Beginning uninstall...";
                cp file1.txt original/path/location;
                break;;
            No ) 
                echo "Stopping uninstall.";
                exit 1;;
        esac
    done
else
    echo "Can't find the folder, package not isntalled."
    exit 1
fi

4 个答案:

答案 0 :(得分:3)

您的代码按预期工作。但您必须输入12而不是yesno

但是我会将第一行更改为:

if [ -d "/tmp/installpackage" ]

-d测试文件是否存在是目录

答案 1 :(得分:0)

我认为在行esac之后你需要一个exit,否则你会有一个无限循环来问你答案

答案 2 :(得分:0)

尝试

if [ -d "/tmp/installpackage" ]
then
    echo "Are you sure you want to uninstall?"
    select yn in "Yes" "No"; do
        case $REPLY in
            Yes ) 
                echo "Beginning uninstall...";
                cp file1.txt original/path/location;
                break;;
            No ) 
                echo "Stopping uninstall.";
                exit 1;;
            *)
                echo "Incorrect choice";
                break;;
        esac
    done
else
    echo "Can't find the folder, package not installed."
    exit 1
fi

答案 3 :(得分:0)

我会首先尝试测试纾困条件,然后再进入卸载代码:

[ ! -d '/tmp/installpackage' ] && \
echo "Can't find the folder, package not isntalled." && exit 1

echo -n 'Are you sure you want to uninstall? [y|n] '
read answer
[[ ! "$answer" = [Yy] ]] && echo 'Stopping uninstall.' && exit 1

echo 'Beginning uninstall...'
cp file1.txt original/path/location