Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How could I modify this INPUT:

/home/USER/Desktop/script.sh

to this OUTPUT:

/home/USER/Desktop/

...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
add comment

4 Answers

up vote 9 down vote accepted

dirname /home/USER/Desktop/script.sh

share|improve this answer
add comment

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
add comment

Using bash:

$ dirname -- "$string"

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

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

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

dir=/home/USER/Desktop/script.sh
echo ${dir%/*}
/home/USER/Desktop
share|improve this answer
1  
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
add comment

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.