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

4
  • 1
    So are you just looking for basename? Commented May 10, 2010 at 18:07
  • Or are you asking about dereferencing symlinks (perhaps with readlink)? Commented May 10, 2010 at 18:07
  • there are many ways to extract the file name from the full path like using basename,cut,awk etc. Commented May 11, 2010 at 12:36
  • see also: stackoverflow.com/questions/192319/… and note that $0 will pull the parent name if you exec the script with source Commented Nov 16, 2016 at 19:12

3 Answers 3

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)"
Sign up to request clarification or add additional context in comments.

1 Comment

This my_scriptname=$(basename "$0") would be better.
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.

Comments

1

basename $0 will give you the script name

1 Comment

basename doesn't strip extensions unless you ask it to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.