Function to get the current script name

I have a function to get the executing scripts name.

Script_nm() {
Parent=$( ps -f -p $PPID -o and | tail -l | sed -e 's/ *[bak]\{1,\}sh *//' | awk '{print $1}' )
If [ $parent = '-bash' ] ; then
Script_nm='bash_test.sh'
Else
Script_nm=$( basename $parent )
Fi
Echo "$script_nm"
Return 0
}

We are calling this function in another script which is used to load the values in the database. This function is not getting the name of the scripts properly. Is there any other logic that can be used for this function ? We have multiple scripts and using the same function to collect the scripts name when they are getting executed. Does adding script_nm=`basename $0` ? work if I add this in all the scripts ?

Would the $BASHPID help? Like

ps hocomm p$BASHPID

this topic has been covered in a couple of threads - including this one.
Also look into the 10 More Discussions You Might Find Interesting section at the bottom of this thread.

1 Like

Since one can't reply to the other thread - closed - I'm curious why none suggested:

script_name=${0##*/}

It does work in bash for sure.
Not so sure about KSH.

Because this kind of question has been asked and answered many times on this site.

That is why no one answered.

It is a forum rule to search the forums before asking questions (like other forums and site) and not ask the same question, over and over again.