Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know the script file name in a Bash script?

How can I determine the name of the Bash script file inside the script itself?

Like if my script is in file runme.sh, then how would I make it to display "You are running runme.sh" message without hardcoding that?

like image 833
Ma99uS Avatar asked Oct 10 '08 17:10

Ma99uS


People also ask

How do I find a filename in bash?

Executing the Bash File to Get File Name and Extension After that, navigate to that directory using the terminal of your choice and type ./filename , which should execute the file. If you are on a Windows operating system, type bash file.sh , and it should run without any problems.

Which command is used to display the script name?

If we prefer not to print the path and only want the name of the script to show, we can use the basename command, which extracts the name from the path.

How do I view a file in a bash script?

Use of `cat` command: The `cat` is a very useful command of bash to create or display the file's content. Any file type can be created easily and quickly by opening the file using the `cat` command with the '>' symbol. Run the following `cat` command to open a file named file1. txt for writing.


1 Answers

me=`basename "$0"` 

For reading through a symlink1, which is usually not what you want (you usually don't want to confuse the user this way), try:

me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")" 

IMO, that'll produce confusing output. "I ran foo.sh, but it's saying I'm running bar.sh!? Must be a bug!" Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms).


1 That is, to resolve symlinks such that when the user executes foo.sh which is actually a symlink to bar.sh, you wish to use the resolved name bar.sh rather than foo.sh.

like image 137
Tanktalus Avatar answered Oct 01 '22 07:10

Tanktalus