Shell script current directory?

LinuxDirectoryShWorking Directory

Linux Problem Overview


What is current directory of shell script? I this current directory from which I called it? Or this directory where script located?

Linux Solutions


Solution 1 - Linux

As already mentioned, the location will be where the script was called from. If you wish to have the script reference it's installed location, it's quite simple. Below is a snippet that will print the PWD and the installed directory:

#!/bin/bash
echo "Script executed from: ${PWD}"

BASEDIR=$(dirname $0)
echo "Script location: ${BASEDIR}"

Solution 2 - Linux

Most answers get you the current path and are context sensitive. In order to run your script from any directory, use the below snippet.

DIR="$( cd "$( dirname "$0" )" && pwd )"

By switching directories in a subshell, we can then call pwd and get the correct path of the script regardless of context.

You can then use $DIR as "$DIR/path/to/file"

Solution 3 - Linux

The current(initial) directory of shell script is the directory from which you have called the script.

Solution 4 - Linux

You could do this yourself by checking the output from pwd when running it. This will print the directory you are currently in. Not the script.

If your script does not switch directories, it'll print the directory you ran it from.

Solution 5 - Linux

To print the current working Directory i.e. pwd just type command like:

echo "the PWD is : ${pwd}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuzan CiocView Question on Stackoverflow
Solution 1 - LinuxkrgView Answer on Stackoverflow
Solution 2 - LinuxsaadaView Answer on Stackoverflow
Solution 3 - LinuxMerouane KHALILIView Answer on Stackoverflow
Solution 4 - LinuxkeyserView Answer on Stackoverflow
Solution 5 - LinuxSachin JavaView Answer on Stackoverflow