How can I write a script that prints the absolute path of the current working directory?
Asked
Active
Viewed 1,641 times
0
-
8`pwd` ......... – Arkadiusz Drabczyk Aug 31 '22 at 11:55
-
3@ArkadiuszDrabczyk Now go and post the shortest answer ever on this website. – Jos Aug 31 '22 at 12:25
-
1You could post the word `pwd` as a link to [man pwd](https://man7.org/linux/man-pages/man1/pwd.1.html). – Jos Aug 31 '22 at 13:50
-
1Alternatively: use the shell's builtin variable `echo "$PWD"` – glenn jackman Aug 31 '22 at 14:03
-
@Jos: only if `pwd` wasn't first a built-in in most shells – Arkadiusz Drabczyk Sep 05 '22 at 17:42
1 Answers
6
If you want to get the directory from which the script is called you can use either the environment variable $PWD or the command pwd in most cases with command substitution like $(pwd).
If you want to get the actual location of the script you can use the variable $0 that contains the full script name (including the path).
Here is an example:
~$ cat /usr/local/bin/test-path.sh
#/bin/sh
echo "${0}" # full script name
echo "${0##*/}" # script name
echo "${0%/*}" # script path
echo "$PWD" # current working directory
echo "$(pwd)" # current working directory
pwd # current working directory
~$ test-path.sh
/usr/local/bin/test-path.sh
test-path.sh
/usr/local/bin
/home/pa4080
/home/pa4080
/home/pa4080
Here is one related topic: What kind of link to /bin/systemctl is /sbin/reboot?
BeastOfCaerbannog
- 12,964
- 10
- 49
- 77
pa4080
- 29,351
- 10
- 85
- 161