2

I got the question when i looking other's shell script.

I saw that declared

APP_NAME="${0##*[\\/]}"

Since I can't find any answer, what's the meaning of this code?

Cyrus
  • 84,225
  • 14
  • 89
  • 153

1 Answers1

5

It's Shell Parameter Expansion to get script name itself, without path

See bash manual:

${parameter##word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching).

If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted.

Pattern Matching:

*

Matches any string, including the null string. When the globstar shell option is enabled, and ‘*’ is used in a filename expansion context

[…]

Matches any one of the enclosed characters.

Explanation

${parameter<...>} expression means that you can expand shell parameters.

I.e. ${1:-"default_arg_value"} will be expanded to "default_arg_value" if script running without arguments.

0 - is a 0th argument, i.e. script name itself

${0##<pattern>} will delete longest matching to <pattern> part of $0

*[\\/] means any string that ends with \ or / symbol.

So, APP_NAME="${0##*[\\/]}" means that $APP_NAME will be initialized by script name itself, without path.

Sample

Let's suppose you have script a/b/c/d/test.sh:

#!/bin/bash
echo "${0##*[\/]}"
echo "${1#*[\/]}"
echo "${2##[\/]}"
$ bash a/b/c/d/test.sh /tmp/e /tmp/ff
> test.sh
> tmp/e
> tmp/ff
Yasen
  • 4,241
  • 1
  • 16
  • 25