Bash string expansion

I saw a script of bash with expansion that I had hard time to understand:

if [[ -z "$@" ]]; then
    echo " ${0##*/} <archive> - extract common file formats)"
    exit
fi
Usage: script.sh file1.gz file2.bz file3 file4.tar

How does ${0##*/} work here?
Spent some time on this, but could not find a direct answer. especially the 0 inside the curly braces. Thanks a lot!

Hi

While $1 to $999 would be arguments passed to the script or function, $0 refers to the executed script.
The ##*/ removes everything before the last /.
It's kind of the 'same' as basename.

Hope this helps

EDIT:
To access a functions name, you would be using $FUNCNAME

1 Like

Hi
Here you can quickly find

LESS=+/Parameter\ Expansion man bash
LESS=+/## man bash

the positional parameter $0 is the name of the script.
We can put everything together and we can come up with an alternative:

echo " $(basename $0) <archive> - extract common file formats)"

That is, if you ran the script like ./script.sh or /home/$USER/script.sh, then you get the output of script.sh

3 Likes

Thanks!
I did not know this is an extension of ${0} and can be found in man bash. Wish Bash had some examples in the manpage. Thanks again!

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.