set current working directory to directory of shell script

How to Set Current Working Directory to Directory of Shell Script

Shell scripts allow you to automate many tasks and processes in Linux. Many of the commands in shell script depend on the present working directory to work properly. Sometimes you may need to set this present working directory to the directory of shell script to avoid errors and allows shell to be able to find commands and files correctly. In this article, we will learn how to set current working directory to directory of shell script.


How to Set Current Working Directory to Directory of Shell Script

By default, when you run shell script, its current working directory is the same as the present working directory from where you have called the shell script. If you want to change the current working directory to directory of shell script, add the following lines to your shell script.

#!/bin/bash
cd "$(dirname "$0")"

In the above command, the first line sets the execution environment. The second line issues the cd command to change present working directory of shell script. In that, we use dirname command to get the directory of shell script. dirname $0 command returns the directory where the Bash script file is located. $() is used for command substitution, that is, $(dirname “$0”) is substituted with the present working directory of shell script.

So when you add the above two lines to your shell script, it will change the present working directory of shell script to the directory of shell script. This is useful if you have relative path references in your shell script, that depend on the folder location of shell script.

In this article, we have learnt how to set current working directory to directory of shell script.

Also read:

How to Change Shutdown Message in Linux
How to Mkdir only if Directory Does Not Exist
How to Create Nested Directory With Single Command
How to Create CA Bundle from CRT Files for SSL Certificates
How to Copy Files from Linux to S3 Bucket

Leave a Reply

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