get current directory of bash script

How to Get Current Directory of Bash Script

Linux allows you to automate tasks using bash scripts. PWD command displays the current working directory in Linux shell. However, you will be surprised to know that PWD is also an environment variable that stores the current working directory value as a string. You can call this variable in your bash script to get current working directory.


How to Get Current Directory of Bash Script

Here is a simple example to get current directory using pwd command as well as $pwd environment variable.

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

Please note, you need to prefix pwd with $ if you refer to environment variable.

Next, we will use them to get current directory of bash script.


1. Create Shell Script

Open terminal and run the following command to create an empty shell script.

$ sudo vi current_dir.sh


2. Get Current Directory

Add the following lines to your shell script to display current directory of 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 display current working directory using pwd shell command as well as $pwd environment variable. We also use OLDPWD environment variable to display previous working directory.


3. Make Shell Script Executable

Run the following command to make shell script executable.

$ sudo chmod +x current_dir.sh


4. Run Shell Script

Run the following command to execute shell script.

$ ./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

If you want to store the result of these commands in variable, you can do so using assignment operator.

curr_dir =$PWD
echo $curr_dir #e.g. /home/ubuntu

You can also append strings to the value of current working directory.

subpath="/data"
new_path = $curr_dir$subpath #e.g. /home/ubuntu/data
echo $new_path  #e.g. /home/ubuntu/data

In this article, we have learnt how to get current directory of bash script using pwd shell script command as well as environment variable. We also learned how to store this value in a variable, and append strings to it to get new paths.

Also read:

Apache Commands Cheat Sheet
How to Clone Git Repository to Specific Folder
How to Switch Python Version in Ubuntu/Debian
How to Disable HTTP Methods in Apache
MySQL Datetime vs Timestamp

Leave a Reply

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