Linux / Unix Shell Script: Get The Current Directory

I am working on a shell script. I need to find out the current working directory. How do I get the current working directory under Bash or Ksh shell running on Linux or Unix like operating systems?

You can use shell variable called PWD or pwd built-in command to get the current working directory. The cd command sets the following shell variable:

[a] OLDPWD The previous working directory as set by the cd command.

[b] PWD The current working directory as set by the cd command.

[c] pwd command – Print the name of the current working directory.


The syntax is:

echo "The current working directory: $PWD"
echo "The previous current working directory: $OPLDPWD"
## use pwd command ##
## or ##
echo "My working dir: $_mydir"

Shell script example

The following script use $PWD twice to set default and provide information to the sys admins.

# Purpose: Set file permission to read-only
# Author: SXI LLC <> under GPL v2.0+
# ---------------------------------------------------------------
# DocumentRoot permissions 
# Apache user/group
## If $1 is not passed, set to the current working dir using $PWD
## Die if $dir does not exists
[ ! -d "$_dir" ] && { echo "Error: Directory $_dir not found."; exit 2; }
## Get confirmation 
echo "I will change file permission for the webserver dir and files to restrictive read-only mode."
read -p "The current working dir is ${PWD}. Are you sure (y / n) ?" ans
## Lowercase $ans and compare it 
if [ "${ans,,}" == "y" ]
      chown -R ${_user}:${_group} "$_dir"
      chmod -R $_fp "$_dir"

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts