如何在 shell 脚本中使用 case esac 进行循环?

如何在 shell 脚本中使用 case esac 进行循环?

我想编写一个脚本,如果用户输入包含他/她的$HOME目录的路径,它会引发错误,并且脚本将运行,直到用户输入循环中断的有效路径。

continue显然,如果我有或命令,它会给出语法错误break。我在这里做错了什么?谢谢,Jen。

#!/bin/bash

function project1_install_dir_path() {   

    boolian_2=true; 
    while true; do

    if [ "$boolian_2" = true ] ; then

       read -p "Enter FULL folder path where you want to install colsim1:" fullpath

       echo "you have enterd "$fullpath". Please press 'y' to confirm and 'n' to enter again"

       case "$fullpath" in

       "$HOME"*) echo "Error: The path cannot be in your HOME" ;; continue      
       */home*) echo "Error: The path cannot contain 'home' in the path" ;; continue
       *) echo "you have entered a valid path" ;; break

       esac
       done    
   fi    
}

function main() {

project1_install_dir_path    
}

终端输出

jen@ss23:/bash_file.sh 
-bash: /project/bash_file.sh: line 62: syntax error near unexpected token `newline'
-bash: /project/bash_file.sh: line 62: ` "$HOME"*) echo "Error: The path cannot be in your HOME" ;; continue  

答案1

你真的应该检查一下你的缩进。虽然你的缩进表明顺序不对,但最后的donefi语句的顺序是错误的。另一个问题是语句case。基本语法是

case $SOMETHING in
    value1)
        statement1;
        statement2;
        ;;
    value2)
        statement3;
        statement4;
        ;;
esac

也就是说:final;;实际上必须是每个案件并表示其结束。如果你想continue在某些情况下,那么你需要把那个continue语句any ;;,像这样:

#!/bin/bash

function project1_install_dir_path() {   

    boolian_2=true; 
    while true; do
        if [ "$boolian_2" = true ] ; then
            read -p "Enter FULL folder path where you want to install colsim1:" fullpath
            echo "you have enterd '$fullpath'. Please press 'y' to confirm and 'n' to enter again"
            case "$fullpath" in
                "$HOME"*) 
                    echo "Error: The path cannot be in your HOME"; 
                    continue;
                    ;;
                */home*)
                    echo "Error: The path cannot contain 'home' in the path";
                    continue;
                    ;;
                *) 
                    echo "you have entered a valid path";
                    break;
                    ;;
            esac
        fi    
    done    
}

function main() {
    project1_install_dir_path    
}

main;

相关内容