37

What does a percent sign mean in bash when manipulating strings? For example, what does ${0%/*} mean?

Vicky
  • 12,934
  • 4
  • 46
  • 54
musthero
  • 1,267
  • 3
  • 13
  • 18

1 Answers1

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
  • 2
    To 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
  • Is that ${1} a reference to the stdin? And can I pipe things into it? – Tom Jul 30 '16 at 00:07
  • @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