Finding a path like /dir1/dir1

I have a script that asks user to input a path like this:

echo "please input path"
read path

This works just fine but I want to make sure that the user inputs the path as /xyz/xyz

In other words, I want to make sure that they use a forward slash for the first part of the path with NO forward slash at the end of the second path. I want to print an error message if they enter it incorrectly. I assume I could use a test condition beginning like this as a start:

tryme=/dir1/dir1/
#if [[ $tryme == '^\/*\/.*[\/]$' ]]; then echo "error";else echo "no error";fi#

However grep correctly matches /dir/dir/ when I use this expression but not the test expression. What am I doing wrong? If the path is /dir1/dir1 "error" should be displayed.

[ $(echo $tryme | egrep -c '\/.*\/.*\/') -eq 0 ] && echo "Correct" || echo "Wrong"

egrep returns 0 if the path is /dir1/dir1 and 1 if it's /dir1/dir1/

1 Like

That solution worked! But I am wondering why my original test condition did not. Is the regex that is used in the test condition different than with the egrep? Or is there something wrong with the syntax?

It would work if you use the match (=~) operator instead:

tryme=/dir1/dir1/
if [[ $tryme =~ ^\/*\/.*[\/]$ ]]; then echo "error";else echo "no error";fi
error

tryme=/dir1/dir1
if [[ $tryme =~ ^\/*\/.*[\/]$ ]]; then echo "error";else echo "no error";fi
no error
1 Like

I could not get your shell expression in post #1 to work - but be assured the ^ and $ char don't have the meaning in shells they have in regexes, unless you use the =~ binary operator (see post #4). What I could get to work is substring expansion (in bash):

 if [ "${tryme: -1}" ==  "/" ]; then echo "error";else echo "no error";fi

means: check if last char is a "/" and, if yes, output "error".