GhostCat GhostCat - 2 months ago 7
Linux Question

bash: any precautions required when opening local file?

I found the following within one of our scripts:

SCRIPT_LOCATION=$(pwd)
SCRIPT_DIRECTORY="$(dirname ${SCRIPT_LOCATION})"
CONFIG_FILE="${SCRIPT_DIRECTORY}/.saved-settings"


The idea is basically: the script then checks if that file exists; and the saved settings are loaded.

It seems that running pwd and dirname ... doesn't add any value. Is the above better than a simple

CONFIG_FILE="./.saved-settings"


If so - in which ways?

Answer

One semantical difference between

SCRIPT_LOCATION="$(pwd)"
SCRIPT_DIRECTORY="$(dirname ${SCRIPT_LOCATION})"
CONFIG_FILE="${SCRIPT_DIRECTORY}/.saved-settings"

and

CONFIG_FILE="../.saved-settings"

(notice the two dots) is in the case when the current directory is a symlink. In that case, dirname will treat the path as a string and will remove the last component of it (e.g. /foo/bar/baz will become /foo/bar), but the .. operator will take you to the parent directory of the symlink target. So if the current directory is /foo/bar/baz which is a symlink to /aaa/bbb/ccc then the first snippet will return /foo/bar whereas the second one will return /aaa/bbb.

Comments