1

Hi I have a small script (script name is: test1.sh) that looks like this

PRG=$0
data=`expr $PRG : '.*\/.*'`
echo $data

When I run this I see output as

10

I could not understand the regular expression written in the second line of the script. What would that mean?

2 Answers 2

2

From

If the match succeeds the `:'
     expression returns the number of characters
     matched.

So the 10 is likely

./test1.sh
^^^^^^^^^^
||||||||| \
123456789 10
Sign up to request clarification or add additional context in comments.

1 Comment

Since the question asked about the meaning of the regular expression, it will match 0 or more of any character, followed by a slash, followed by 0 or more of any character. The expr command matches specifically from the beginning of the input string. So this explains why it would match the entire string, if $0 == "./test1.sh". Also note that $0 in a bash script refers to the script name, as this answer implies.
1

The expression returns a non-zero value if there is a / within the relative filename of the script ($0 in sh). If you execute the script like this: sh ../../script.sh, it outputs 15, which is the total length of "../../script.sh". It matches "../../" with '.*\/ and matches script.sh with the .* part.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.