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:
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash/Ksh
Est. reading time N/A
[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.

Syntax

The syntax is:

echo "The current working directory: $PWD"
echo "The previous current working directory: $OPLDPWD"
_cwd="$PWD"
 
## use pwd command ##
_mydir="$(pwd)"
 
## or ##
_mydir="`pwd`"
 
echo "My working dir: $_mydir"

Shell script example

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

#!/bin/bash
# Purpose: Set file permission to read-only
# Author: nixCraft <www.cyberciti.biz> under GPL v2.0+
# ---------------------------------------------------------------
# DocumentRoot permissions 
_dp="0544"
_fp="0444"
_sp="0744"
 
# Apache user/group
_user="www-data"
_group="www-data"
 
## If $1 is not passed, set to the current working dir using $PWD
_dir="${1:-${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" ]
then
      chown -R ${_user}:${_group} "$_dir"
      chmod -R $_fp "$_dir"
fi

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 1 comment so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
1 comment… add one
  • Kumar Sep 26, 2013 @ 6:14

    i want Unix Shell Script: Get The full Directory path.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum