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
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 1 comment… read it below or add one }
“Its location” not “it’s location”.