How to loop with case esac in shell scripting?

I'd like to write a script where if a user enters a path which contains his/her $HOME directory, it would raise an error and the script will run until user enters a valid path in which the loop will break.

Apparently it gives a syntax error if I have continue or break commands. What do I do wrong here? Thanks, 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
}

Terminal Output

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

1 Answer

You should really check your indentation. The final done and fi statements are in the wrong order although your indentation suggests otherwise. Another issue is the case statement. The basic syntax is

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

That is: the final ;; must actually be the last statement for each case and indicates its end. If you want to continue in some case, then you need to put that continue statement before any ;;, like so:

#!/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;
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like