Bash: get absolute path to current script
There can be many reasons why you'd want to get the exact location of your currently running script. For example to calculate the relative path in a reliable way.
Luckily there is a command called realpath that will calculate and print the absolute path of a given path.
Let's see how it works:
examples/shell/absolute.sh
#!/bin/bash echo $0 full_path=$(realpath $0) echo $full_path dir_path=$(dirname $full_path) echo $dir_path
$0 is the name of the current script as it was executed. So if we run the script as ./examples/shell/absolute.sh then that will be the content of $0.
realpath prints the abosulte path.
dirname prints the directory name, leaving the last part of the path which is in this case the name of the file.
Let's see a couple of examples:
$ ./examples/shell/absolute.sh ./examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell
$ cd examples/shell/ $ ./absolute.sh # run right where it is ./absolute.sh /home/gabor/work/code-maven.com/examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell
$ cd ../../sites/en # go to a cousin of the scripts directory $ ../../examples/shell/absolute.sh # run relatively from there ../examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell
$ ln -s ../../examples/shell/ # create a symbolic link to the directory $ ./shell/absolute.sh # run using the symlink ./shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell
$ ln -s ../../examples/shell/absolute.sh # create a symlink to the script $ ./absolute.sh # run using the symlink ./absolute.sh /home/gabor/work/code-maven.com/examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell
$ /home/gabor/work/code-maven.com/examples/shell/absolute.sh # run with full path /home/gabor/work/code-maven.com/examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell/absolute.sh /home/gabor/work/code-maven.com/examples/shell
Published on 2019-05-22