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
url=http://www.foo.bar/file.ext; echo ${url##/*}

I expected this code to print file.ext, but it prints the whole URL. Why? How can I extract the file name?

share|improve this question
Okay obv I am expecting the wrong things to happen. Well I want to extract file.ext – ManuelSchneid3r Feb 11 '13 at 14:41
You're trying to cut the end off the string? Try dirname $url. Or grep -o 'http://[^/]*' <<<$url. – Kevin Feb 11 '13 at 15:04
up vote 6 down vote accepted

Because word has to match the string to be trimmed. It should look like:

url="http://www.foo.bar/file.ext"; echo "${url##*/}"

Thanks derobert, you steered me in the right direction.

share|improve this answer
Hah, we both realize that at the same time. Glad to be of help. – derobert Feb 11 '13 at 14:51

To quote the manpage:

   Remove matching prefix pattern.  The word is expanded to produce
   a pattern just as in pathname expansion.  If the pattern matches
   the  beginning of the value of parameter, […]

/* does not match the beginning, because your URL starts with h not /.

A trivial way to do what you're looking for (according to your comment) is echo "$url" | rev | cut -d / -f 1 | rev. But of course, that'll give interesting results for URLs ending in a slash.

Another way to do what you want might be to use the pattern */ instead.

share|improve this answer

See also: Bash Extended Globbing, though in this case the extended glob is not essential.

 shopt -s extglob; url=http://www.foo.bar/file.ext; echo ${url##+(*/)}

Output: file.ext

share|improve this answer

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.