It identifies the directory that contains the script (which might be different than the current working directory).
You'd commonly use a pattern like this if you needed to refer to files in the same directory:
# contents of myscript.sh
DIR=$( cd $(dirname $0) ; pwd)
cat $DIR/some-file-next-to-my-script.txt
Then from anywhere on the file system:
/path/to/myscript.sh
would actually print the contents of some-file-next-to-my-script.txt
. If you stuck to pwd
alone, you'd be looking for that file in your current working directory, which may or may not be the behavior you want.
Breaking down the command:
$( cd $(dirname $0); pwd)
^^^^^^^^^^
That identifies the directory containing $0
. If you invoked the script as /path/to/myscript.txt
, then dirname $0
evaluates to /path/to
. If you invoked it as ./myscript.txt
, then dirname $0
simply evaluates to .
.
$( cd $(dirname $0); pwd)
^^^^^^^^^^^^^^^^^^^^ ^
Change to the directory as before, but critically, in a subshell so that your working directory isn't modified.
Then the final pwd
simply prints out that current working directory, which will always be expanded to the full path. That value is then stored in the DIR
variable in your example.