Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm running a Bash script that's buried in a directory on my system. I need to be able to get the first section of the directory path.

The path returned by $0 in my script is as below. The "path/to/script" section is constant; the "/variable/path/to/folder" is permanent.

/variable/path/to/folder/main-folder/path/to/my-script.sh
------------------------

I need the underlined section. I've tried cut -d/ -f-4 and cut -d/ -f4-, but cut indexes from the front of the path, and I need to index from the back. (I don't know how many levels will be between / and main-folder, but I do know how many will be between main-folder and my-script.sh. The path here is accurate: there are two folders in main-folder before you get to my-script.sh.)

share|improve this question

1 Answer 1

up vote 3 down vote accepted

How about this?

echo ${0%/*/*/*/*}
share|improve this answer
    
I added an extra */ to get exactly what I wanted. (I.e., THINGY=${0%*/*/*/*/*}.) Can you explain why this works? I've not seen this construct before. –  CajunLuke Apr 26 '12 at 23:10
    
It's a form of bash parameter expansion. The characters following the % are a pattern just as in pathname expansion. If that pattern matches some part of the expansion of the parameter ($0 in this case) from the right, the value of the expression is the expansion of the parameter with the matching part removed. The official explanation can be found in the bash(1) man page. Search for the section on "Parameter Expansion" and look for ${parameter%word}. –  garyjohn Apr 27 '12 at 0:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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