5

I launch script.sh and inside it i want to know what is his name

Is there a standard procedure to know the scripts name ? the idea is to be able to extract the name from teh full path + name contained in $0

Thanks

Debugger
  • 9,130
  • 17
  • 45
  • 53
  • 1
    So are you just looking for `basename`? – Cascabel May 10 '10 at 18:07
  • Or are you asking about dereferencing symlinks (perhaps with `readlink`)? – Cascabel May 10 '10 at 18:07
  • there are many ways to extract the file name from the full path like using basename,cut,awk etc. – Vijay May 11 '10 at 12:36
  • see also: http://stackoverflow.com/questions/192319/how-do-i-know-the-script-file-name-in-a-bash-script and note that $0 will pull the parent name if you exec the script with source – iletras Nov 16 '16 at 19:12

3 Answers3

11

Yes, $0 will always contain the name of the script. Use basename to extract the name.

basename /some/really/long/dir/path/myscripts/coolscript.sh will print coolscript.sh

So in your script, you could do this:

my_scriptname="$(basename $0)"
Cascabel
  • 479,068
  • 72
  • 370
  • 318
seamus
  • 445
  • 3
  • 5
3
script="${0##*/}"

Edit:

This does the same thing as basename $0. It strips off the last slash and everything before it from $0 using Bash's brace expansion.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
1

basename $0 will give you the script name

Vincent Robert
  • 35,564
  • 14
  • 82
  • 119