Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

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

How could I modify this INPUT:


to this OUTPUT:


...using bash or perl?

Of course script.sh could be anything: (e.g. scrasdfipt.sh, etc) and the path before it could be anything.

share|improve this question
up vote 9 down vote accepted

dirname /home/USER/Desktop/script.sh

share|improve this answer

For the exact question, you can use

printf "$(dirname /home/USER/Desktop/script.sh)/"

I'm guessing this is an X-Y problem, and you want to refer to a file in the same directory as the current script. If so:

current_dir="$(dirname -- "$0")"

At this point you can do stuff like

source "${current_dir}/foo.sh"
echo foo > "${current_dir}/bar.txt"
share|improve this answer

Using bash:

$ dirname -- "$string"

You can also get the last bit the same way like this:

$ basename -- "$string"
share|improve this answer

In addition to the dirname proposed, you can also remove a susbstring using parameter expansion:

echo ${dir%/*}
share|improve this answer
Note that if the original string contains no directory information, $dir will end up identical to it. Fix: case "$file" in */*) dir="${file%/}";; *) dir=".";; esac – Gilles Jul 29 '11 at 11:32

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.