Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you access the base filename of a file you are sourcing in Bash?

I am sourcing a file in a bash terminal that needs to export some environment varibles.

Example:

source linux_x86.env

the env file looks kinda like this:

export ARCH=/home/user/project/linux_x86

I have a bunch of different architectures to compile for and I want be able to do something like this:

export ARCH=/home/user/project/`basename $0 .env`

where basename $0 .env would give me the basename the env file

bash linux_x86.env
linux_x86

The above will work is a bash script but doesn't seem to work when you source the file.

Is there any way to get the same behavior from source?

like image 214
hacintosh Avatar asked Jul 24 '09 16:07

hacintosh


1 Answers

See Getting the source directory of a Bash script from within, particularly the comment regarding the BASH_SOURCE variable.

Summary: SCRIPT_NAME=$(basename ${BASH_SOURCE[0]})

like image 59
Andrew Barnett Avatar answered Nov 15 '22 17:11

Andrew Barnett