-1

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

#!/bin/bash

function user_input () {

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

        string1="${HOME}"
        echo "$string1"

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

function main() {

user_input
}

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
/ort/home/j/jen
valid path

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

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

[1]https://stackoverflow.com/questions/2237080/how-to-compare-strings-in-bash

  • 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
2

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" ;;
esac

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.