Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


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 The path here is accurate: there are two folders in main-folder before you get to

share|improve this question
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


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.