Pages

Monday, 17 June 2019

bash tips --- How to get the running script's location


Sample code:

#!/bin/bash

SELF_PATH=$(cd $(dirname $0) && pwd)
echo $SELF_PATH

Description:

"dirname" only strip the last component from the file name. It does NOT care if the file exists or not. It knows nothing about relative or absolute directory at all.

"pwd" prints the running process's absolute current directory.

Because the "cd" runs in a subshell, so it won't affect the script's shell at all.

No comments:

Post a Comment