get current directory in linux

How to Get Current Directory in Shell Script

Sometimes you may need to get current working directory in shell script. You can easily do this using pwd command or PWD environment variable. In this article, we will look at how to get current directory in shell script using these two methods.


How to Get Current Directory in Shell Script

You can use built-in shell command pwd or shell variable $PWD to get current working directory as per your requirement. We will look at how to use both of them below.

Here is an example of how to use them in shell terminal.

$ pwd
/home/ubuntu
$ echo $PWD
/home/ubuntu

Now we will create a shell script to demonstrate the above two ways to get current directory.


1. Create Shell Script

Open terminal and run the following command to create a blank shell script.

$ sudo vi current_dir.sh


2. Get Current Directory

Add the following lines to your Shell Script.

 !/bin/sh

 echo "current directory using pwd command"
 echo $(pwd)

 echo "current directory using PWD variable"
 echo $PWD

 echo "previous working directory using OLDPWD variable"
 echo $OLDPWD

Save and close the file. In the above code, we specify shell script execution environment. Then we display current path using pwd command. Next, we display present working directory using PWD shell variable. Finally, we display the previous working directory using OLDPWD shell variable.


3. Make Shell Script Executabe

Run the following command to make it executable.

$ sudo chmod +x current_dir.sh


4. Run shell script

Run the shell script to verify output

 $ ./current_dir.sh

current directory using pwd command
/home/ubuntu

current directory using PWD variable
/home/ubuntu

previous working directory using OLDPWD variable
/etc/data

You may also store the result of either of these commands in a variable and append strings to get more path values. Here is an example

#!/bin/sh

path =$PWD
echo $PWD #/home/ubuntu
subpath="/data"
new_path = $path$subpath #/home/ubuntu/data
echo $new_path #/home/ubuntu/data

In this article, we have learnt how to get current working directory in shell script using pwd command as well as using PWD environment variable. You may use either of them depending on your requirement. They both give same result. You may also append other strings to them to construct new path values.

Also read:

How to Get Current Directory in Python
How to Check Dependencies for Package in Linux
How to Iterate Over Multiple Lists in Python
How to Disable GZIP Compression in Apache
How to Install Specific Version of NPM Package

Leave a Reply

Your email address will not be published. Required fields are marked *