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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With