I'd like to write a regex in shellscript which would compare the user input path to user$HOME. Then it would raise an error in case the user input path contains the user $HOME. The home folder normally starts with /ort/home but /ort part is not a must. When I run it always gives a valid path although I clearly enter an invalid path. What am I doing wrong? Thanks. Please refer following link[1] if necessary to see how regex are used in shellscript

My attempt is as follows


function user_input () {

        read -p "Type the path for project1:" user_path

        echo "$string1"

        if [ "$user_path" = "$string1 | /ort/home/+.* |  .*+/home/+.*"  ]; then 
             echo "Not a valid path, contains $HOME directory"        
             echo "valid path"

function main() {



Terminal output

Please note first entry is a valid path and other two are invalid paths.

jenny@server32:~$ ./test.sh 
Type the path for project1:/scratch/random
valid path

jenny@server32:~$ ./test.sh 
Type the path for project1:/ort/home/j/jen
valid path

jenny@server32:~$ ./test.sh 
Type the path for project1:/ort/home
valid path


  • 2
    Regular expression comparison and string (glob pattern) comparison are different things, with different operators in bash (=~ versus == or =); additionally, =~ is only supported within extended test brackets [[ ... ]] afaik – steeldriver Apr 1 at 22:32

The case command uses glob wildcards which are pretty easy to work with:

case "$user_path" in
    "$HOME"*) echo "Error: path cannot be in your HOME" ;;
    */home/*) echo "Error: cannot have 'home' in the path" ;;
    *) echo "Thank you, valid path" ;;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.