Sometime we want to know the file name of the script which we are executing in bash scripting. One such scenarios is use the file name for logging purpose, without hardcoding the name of the script file.

In the below example, readlink prints out the value of a symbolic link. If it isn’t a symbolic link, it prints the file name.

echo $(basename $(readlink -nf $0))

-f option tells the bash to follow the link completely, until actual file is found.

We can also use BASH_SOURCE to get the file name as illustrated in the following example.

#!/usr/bin/env bash

self=$(readlink -f "${BASH_SOURCE[0]}")
basename=$(basename "$self")

echo "$self"			# /local/mnt2/workspace/demo.sh
echo "$basename"		# demo.sh

BASH_SOURCE is environment variable. It is an array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined.

Pass Arguments

Passing argument to bash script is very common use case. It makes script more generic and increases the utility for scripting. Below example shows how to pass argument and access the passed argument in the script.

#!/bin/bash

echo
echo "# Arguments Passed --->  ${@}     "
echo "# First Argument  ---->  $1       "
echo "# Path  -------------->  ${0}     "
echo "# Parent path -------->  ${0%/*}  "
echo "# File name ---------->  ${0##*/} "
echo
exit

Second echo prints all the argument passed to the bash script. To pass argument to script, use below syntax

# Invocation
 ./demo.sh arg1 arg2

After execution, you should get the below as output. Argument passed are accessed using $, followed by number. In this case 1 refers to first argument and so on.

# Arguments Passed --->  arg1 arg2
# First Argument  ---->  arg1
# Path  -------------->  ./demo.sh
# Parent path -------->  .
# File name ---------->  demo.sh 

We can also get the file name and parent path as shown in above example.