What does it mean SCRIPTNAME = "$ {0 ## * /}" in a shell script? `

This code is sent from the apache2 service starting from the script.

What does it mean?

SCRIPTNAME="${0##*/}"

      

+3


source to share


2 answers


It finds the name of the running script by deleting its directory. For example, if script is equal /etc/init.d/httpd

then this will set SCRIPTNAME=httpd

.

$0

or ${0}

is the name of the script being executed. The operator is ##

used to remove any leading line that matches a pattern */

. *

is a wildcard, so it */

means "any string followed by a forward slash".

The effect of this is to remove any leading directory names from $0

, leaving only the script name.



From man bash :

$ {parameter # word}
$ {parameter ## word}

The word expands to create a template in the same way as expanding a path. If the pattern matches the beginning of the parameter value, then the expansion results in the extended parameter value with the shortest match pattern (case "#") or the longest match pattern (case "##") is removed. If the parameter is @

or *

, the template deletion operation is applied in turn on each positional parameter, and the expansion is the resulting list. If the parameter is an array variable tuned with @

or *

, the delete pattern operation is applied to each member of the array in turn, and the expansion is the resulting list.

+2


source


The left side is simple: it assigns to a variable SCRIPTNAME

. The right side is harder:

  • $0

    or ${0}

    is the name used to invoke the current shell or script.
  • ${VAR##pattern}

    - the value of the variable $VAR

    with the longest string that matches pattern

    , removed from the leading (use one #

    for shortest or %

    / %%

    to remove the end.


This way your expression removes the beginning of the name used to call the script before and including the last slash.

By the way, this is what the program does basename

.

+2


source







All Articles