Linux脚本无法正常工作

时间:2014-11-24 22:33:35

标签: linux shell sh

我有一个脚本,由于某种原因,它似乎是一个跳过一步。

[2]) echo "Delete a User"
read -p "What is the user that you would wish to delete?" username
egrep "^$username" /etc/passwd > /dev/null
if [ $? -eq 0 ]; then
read -p "Do you want to delete their home directory also? 1(yes)/2(no)" home
else
echo "That user does not exist"
sleep 3
if [ $home -eq 1 ]; then
userdel -r $username
else
userdel $username
if [ $? -eq 0 ]; then
echo "$username deleted."
sleep 3
else
echo "$username was not deleted."
sleep 3
fi fi fi
;;

直到我询问用户是否想要删除他们的主目录。如果我点击是或否,它只是跳过并转到脚本的菜单..

2 个答案:

答案 0 :(得分:0)

缩进代码会使问题变得非常明显:

read -p "What is the user that you would wish to delete?" username
egrep "^$username" /etc/passwd > /dev/null
if [ $? -eq 0 ]; then
    read -p "Do you want to delete their home directory also? 1(yes)/2(no)" home
                                  # <-- 2
else
    echo "That user does not exist"
    sleep 3
    if [ $home -eq 1 ]; then      # <-- 1
        userdel -r $username
    else
        userdel $username
        if [ $? -eq 0 ]; then
            echo "$username deleted."
            sleep 3
        else
            echo "$username was not deleted."
            sleep 3
        fi
    fi
fi

我标记为<-- 1的行及其后面的所有行似乎都属于标记为<-- 2的位置 - 测试$home的值只有意义在阅读了它的值之后。

答案 1 :(得分:0)

这是正确缩进时脚本的外观。您可以看到,在您从用户那里获得有关删除主目录的输入之后,所有内容都在其他内容中无法执行

echo "Delete a User"
read -p "What is the user that you would wish to delete?" username
egrep "^$username" /etc/passwd > /dev/null
if [ $? -eq 0 ]; then
    read -p "Do you want to delete their home directory also? 1(yes)/2(no)" home
else
    echo "That user does not exist"
    sleep 3
    if [ $home -eq 1 ]; then
        userdel -r $username
    else
        userdel $username
        if [ $? -eq 0 ]; then
            echo "$username deleted."
            sleep 3
        else
            echo "$username was not deleted."
            sleep 3
        fi 
    fi 
fi

应该看起来像这样

echo "Delete a User"
read -p "What is the user that you would wish to delete?" username
egrep "^$username" /etc/passwd > /dev/null
if [ $? -eq 0 ]; then
    read -p "Do you want to delete their home directory also? 1(yes)/2(no)" home
else
    echo "That user does not exist"
    sleep 3
fi
if [ $home -eq 1 ]; then
    userdel -r $username
else
    userdel $username
    if [ $? -eq 0 ]; then
        echo "$username deleted."
        sleep 3
    else
        echo "$username was not deleted."
        sleep 3
    fi 
fi