$0
In order to change the current working directory to the script's directory, put the following command right after the shebang line:
cd "$(dirname "$0")"
The $0
variable expands to the script name (path to the script), and dirname
returns path to the script's directory.
Detecting the current working directory
You can use pwd
command to get the current working directory. If you are actually running Bash (I'm not sure, since the shebang in your code points to /bin/sh
), you can use the built-in $PWD
variable:
PWD
The current working directory as set by the cd
builtin.
Storing the script's path into variable
Alternatively, save the directory path into a variable, and use it in the script, e.g.:
dir="$(cd $(dirname "$0"); pwd)"
chmod 770 "$dir/somefile"
Double quotes
Note the use of double quotes. Double quotes prevent reinterpretation of special characters. It is also the way to pass strings containing spaces as a single word:
dir="some directory name"
cd "$dir"
Without double quotes the words are interpreted as separate arguments.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…