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:
#!/bin/bash # 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:
When you run
$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