Bash source Command: $0 Can Not Determine Its Own Location

The source command read and execute commands from a file. My parent.sh script source a script called child.sh. But, child.sh script can not determine it’s own location using $0. By default, $0 gives parent script location. How do I find out a script that is sourced at the command line can determine it’s own location? My sample script:

#!/bin/bash
# /var/www/html/java/tasks/child.sh 
_me="$0"
 
 
# I want /var/www/html/java/tasks in _currentdir 
_currentdir="${_me%/*}"
echo "${_currentdir}"

When I run from parent.sh:

source child.sh

OR

source /var/www/html/java/tasks/child.sh

The $_currentdir is set to be the directory where parent.sh lives which is in /root/scripts/java/helper or . (current) directory. How do I fix this problem?

You need to use an array variable called BASH_SOURCE whose members are the source filenames corresponding to the elements in the FUNCNAME array variable. This variable available since bash version 3.x+. To fix your problem, fix child.sh script as follows:

#!/bin/bash
# /var/www/html/java/tasks/child.sh 
# get child.sh location using the following array
 
###################################################################
# *** Warning it will only work with bash 3.0 and above only **** #
###################################################################
_me="${BASH_SOURCE[0]}"
 
# Fixed 
_currentdir="${_me%/*}"
 
echo "${_currentdir}"

Test it as follows:

cd /tmp
pwd
source /var/www/html/java/tasks/child.sh

Sample outputs:

/var/www/html/java/tasks

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 1 comment so far... add one

CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
1 comment… add one
  • reņģis May 11, 2012 @ 7:41

    “Its location” not “it’s location”.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @ webmaster@cyberciti.biz