Change directory working directory in shell script

I am trying to write a simple shell script, which will change the directory to the shell script directory and echo it.

This is the script:

# cd '/explicit/path/to/script'
cd $(dirname $0)
echo $(dirname $0)

The output indeed is always, even if I use an explicite cd to the script dir.


What am I missing?


You need to run the script instead of sourcing it:


(without .).

When you run

. /path/to/

$0 is your current shell, which is presumably in /bin (hence the behaviour you’re seeing). Note that it needn’t be /bin/bash, the shebang doesn’t have any effect when sourcing a script.

Lucas‘ other points are valid, you should use quotes and just run dirname directly, without echo.

Leave a Reply

Your email address will not be published. Required fields are marked *