test.sh
Code:
prog1=$(echo $0 | sed 's/.*\///g;s/\.sh//g')
echo $prog1
If you run
./test.sh
test
the response was test
If however, you source the file, the response is bash
With sourcing, the result of $0 is the name of the calling script
in place of echo and sed
test.sh
Code:
prog1=$(basename $0 .sh)
echo "$prog1 is my script name"
Please note: $0 changes when the script is sourced.
If you are going to source your script, you would need test.sh as an argument to another script.
test2.sh
Code:
#!/bin/bash
prog1=$(basename $1 .sh )
Now ./test2.sh test.sh
yields test
and
. ./test2.sh test.sh
yields test.
Why do we want to do this anyway. Well here is a situation
Suppose I have a group of directories titled project1, project2, project3, ...
and my "project1.sh", "project2.sh", "project3.sh" ... script have
Code:
#!/bin/bash
prog1=$(basename $0 .sh)
cd $prog1
ls -l | grep -v total
#
If I do project1.sh
I will see the contents of project1
If I want to also switch to project1
I would just like to do
. project1.sh
to switch to that directory and after the listing, to become my current directory.