What does a percent sign mean in bash when manipulating strings? For example, what does ${0%/*}
mean?
Asked
Active
Viewed 2.3k times
37
-
13You can check it in http://tldp.org/LDP/abs/html/refcards.html#AEN22664 – fedorqui May 08 '13 at 15:01
-
1New link to "String Operations" docs: http://tldp.org/LDP/abs/html/refcards.html#AEN22828 – Beau Smith Aug 07 '16 at 19:40
-
1See also https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Parameter-Expansion. – melpomene Aug 15 '19 at 11:00
-
This question should be marked a duplicate of https://stackoverflow.com/q/34951901 instead of the other way around. – Henke Feb 08 '22 at 14:05
1 Answers
37
If you use @fedorqui's resource, you'll see it is going to strip the shortest match of /*
from the end of the first positional argument. An example:
example_foo(){
echo ${1%/*}
}
example_foo path/to/directory/sub_directory
# => path/to/directory
In the example I used the second positional argument since the first is the name of the function.

Ian Stapleton Cordasco
- 26,944
- 4
- 67
- 72
-
2To address the original question, `$0` is the full pathname of the script being executed; the given expression strips off the final component of the path, so it is roughly equivalent to `dirname $0`. – chepner May 08 '13 at 15:24
-
As I understand it, the `1` in the example indicates the second fragment of the command, counting from 0. – Nicolas Barbulesco Aug 29 '14 at 12:40
-
@NicolasBarbulesco that is correct. You might also hear "fragment" referred to as "argument" though. – Ian Stapleton Cordasco Aug 29 '14 at 13:29
-
-
@Tom, $1 refers to `path/to/directory/sub_directory` which is the 1st argument to `example_foo`. You cannot pipe things into it. – Ian Stapleton Cordasco Jul 30 '16 at 01:04
-
Quotes are important. `echo ${1%/*}` can show incorrect output in cases where `echo "${1%/*}"` is correct; consider, for instance, following `set -- '*/foo'` -- the former will list files in the current directory. – Charles Duffy Jan 25 '17 at 19:21