Shell脚本无法正常工作

时间:2015-10-04 23:26:22

标签: shell tcsh

我的shell脚本存在一些问题。第一个问题是,如果我在提示用户时输入“No”或“n”,我会收到错误消息“No endif”。我的3个endif在这种情况下不起作用吗?

此外,我的for循环应该检查文件是否已更改,如果它没有复制它,如果它已复制它。但是我的比较不起作用,每次都复制每个文件。

#!/usr/bin/tcsh

if (! -d backup ) then
    echo "The backup folder does not exist.  Would you like to create it?  Y for Yes N for No"
    set userAnswer=$<
    if ($userAnswer == "yes" || $userAnswer == "y"|| $userAnswer == "Y" || $userAnswer == "YES") then
        mkdir backup
        else if ($userAnswer == "no" || $userAnswer == "n"|| $userAnswer == "N" || $userAnswer == "NO") then
            echo "No directory created"
            else
                echo "Invalid response"
                exit 1
            endif
        endif
    endif
else
foreach i ( *.c )
    if ("$i" == "/backup/$i") then
        echo file has not changed
    else
        cp $i backup
        echo test
    endif
end
endif

3 个答案:

答案 0 :(得分:1)

在第一行和 else 语句之间有一组缩进行,大约有13行。这个块有一个嵌套的if / else if / else / endif语句,其中只有一个endif:

if ($userAnswer == "yes" || $userAnswer == "y"|| $userAnswer == "Y" || $userAnswer == "YES") then
    mkdir backup
else if ($userAnswer == "no" || $userAnswer == "n"|| $userAnswer == "N" || $userAnswer == "NO") then
    echo "No directory created"
else
     echo "Invalid response"
     exit 1
endif

答案 1 :(得分:1)

使用switch可能会简化代码:

#!/usr/bin/tcsh

if (! -d backup ) then
    echo "The backup folder does not exist.  Would you like to create it?  Y for Yes N for No"
    set userAnswer=$<
    switch ($userAnswer)
        case [yY][eE][sS]:
            echo "Answer was yes"
            breaksw
        case [yY]:
            echo "Answer was yes"
            breaksw
        case [nN][oO]:
            echo "Answer was no"
            breaksw
        case [nN]:
            echo "Answer was no"
            breaksw
     endsw
    # ....
endif

答案 2 :(得分:0)

如果你有3个endif,你只需要1 ...(我认为)sh FanBoy *