zachboy82 zachboy82 - 4 months ago 8
Bash Question

How do I get the directory from where I call the script when the script itself is in a different directory?

I am making a few custom commands to use on my debian server and I am putting them in the /usr/bin folder.

One custom command I wish to make involves getting the directory from where I call the script, NOT the directory in which the script resides.

Nearly all of the questions I find on here involve getting the working directory using

a=$PWD


or

a=$(pwd)


This only returns the directory in which the script resides.

Edit: I am aware of

$OLDPWD


The above will only work some of the time.

Is it possible to do what I want?

Current form of my script:

#!/bin/bash
if [ -z "$1" ]
then
a=$(pwd)
echo "Unlocking current directory."
sudo chmod 777 -R $a
else
echo "Unlocking directory at \"$1\""
sudo chmod 777 -R $1
fi

Answer

One custom command I wish to make involves getting the directory from where I call the script,

Try this

#!/bin/bash
pwd

Contrary to what you've mentioned pwd should give you the place from where the script is called

Sample run

user@host:~/Documents/so$ ./myscript.sh
/home/me/Documents/so
user@host:~/Documents/so$ cd ..
user@host:~/Documents$ ./so/myscript.sh 
/home/me/Documents

To the contrary, if you wish to know where you script exists from within you script - no matter from where it is called - do

#!/bin/bash
script_path="$(which $0)"
readlink -m "$script_path" 
which ls # no need for readlink for standard commands like ls
Comments