Do NOT get into this messy shit if you can avoid it! Use Python script instead if you can.
If you want to reliably get the name of a Bash script, it is recommended that you run the Bash script as an executable script instead of source it in.
There are 2 ways (
$0
and${BASH_SOURCE[0]}
) to get the file name of a Bash script.${BASH_SOURCE[0]}
is a more robust way and is preferred.
Get File Name Without Parent Directory¶
In [1]:
!basename /scripts/sys/etc.sh
Get File Name and Extensions¶
In [3]:
%%bash
FILE="example.tar.gz"
echo "${FILE%%.*}"
echo "${FILE%.*}"
echo "${FILE#*.}"
echo "${FILE##*.}"
$0
vs ${BASH_SOURCE[0]}
¶
The example below shows that ${BASH_SOURCE[0]}
is more robust than $0
and is preferred.
In [22]:
# print the content of a Bash script a.sh
!cat bash-file-name/a.sh | highlight -O ansi
Running the Bash script as an executable script.
In [20]:
!bash-file-name/a.sh
Source in the Bash script.
In [21]:
%%bash
source bash-file-name/a.sh
On Symbolic Links¶
Both $0
and ${BASH_SOURCE[0]}
work on symbolic links.
You can use readlink
to get the raw path of the file.
In [27]:
# create a symbolic link to a.sh as b.sh
!ln -svf $(realpath bash-file-name/a.sh) bash-file-name/b.sh
In [28]:
!bash-file-name/b.sh
In [29]:
%%bash
source bash-file-name/b.sh
Running from Another Script¶
In [36]:
# c.sh runs a.sh
!cat bash-file-name/c.sh | highlight -O ansi
In [32]:
!bash-file-name/c.sh
In [34]:
%%bash
bash-file-name/c.sh