I want to design bash script in unix and this bash return full path because I want to use this file in other places.
-
Full path of what? Self, as in the full path of the running script or some other object? A text string passed to your script as an argument? – Caleb Oct 04 '10 at 14:10
-
critically you did not say whether you are executing or sourcing the script as it imparts very different approaches to solving the path question – Scott Stensland Mar 15 '18 at 02:28
3 Answers
Give this a try if you have readlink
on your system:
readlink -e filename
![](../../users/profiles/1293.webp)
- 60,515
- 14
- 113
- 148
-
i try to execute it and this is a result ` readlink: not found` – Mohammad AL-Rawabdeh Oct 04 '10 at 13:57
-
Are you looking for the full path and filename of the running script?
#!/bin/bash
_my_name=basename $0
if [ "echo $0 | cut -c1
" = "/" ]; then
_my_path=`dirname $0`
else
_my_path=`pwd`/`echo $0 | sed -e s/$_my_name//`
fi
echo " Filename: $_my_name"
echo "Absolute path: $_my_path"
echo "Full Path + Name: $0"
![](../../users/profiles/15561.webp)
- 624
- 5
- 9
-
1@Osama Ahmad: See [BashFAQ/028](http://mywiki.wooledge.org/BashFAQ/028). – Dennis Williamson Oct 04 '10 at 14:32
Since this question is not trying to answer the harder question of converting a path with symbolic links into a physical path (w/o any links), but rather just get the directory and/or full path to the original script, there is a simpler solution (broken down in this example into components for legibility, plus you may want to use any of these pieces individually):
#!/bin/bash
PROG_PATH=${BASH_SOURCE[0]} # this script's name
PROG_NAME=${PROG_PATH##*/} # basename of script (strip path)
PROG_DIR=$(cd "$(dirname "${PROG_PATH:-$PWD}")" 2>/dev/null 1>&2 && pwd)
echo "script directory is: $PROG_DIR"
Your test cases should involve calling this script with an absolute path, relative path, "sourcing" it, etc., and always ending up with the directory containing the script.
![](../../users/profiles/80415.webp)
- 384
- 1
- 5