How to set current working directory to the directory of the script in bash?

jameshfisher picture jameshfisher · Jul 28, 2010 · Viewed 411.6k times · Source

I'm writing a bash script. I need the current working directory to always be the directory that the script is located in.

The default behavior is that the current working directory in the script is that of the shell from which I run it, but I do not want this behavior.

Answer

ndim picture ndim · Jul 28, 2010
#!/bin/bash
cd "$(dirname "$0")"