0

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
zkirkland
  • 12,175
  • 3
  • 16
  • 18

1 Answers1

1

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 
readlink -m "$(which $0)" #method1
readlink -m "${BASH_SOURCE}" #method2 , preferred for reasons mentioned by @CharlesDuffy's comments
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • I did try that just now and as you stated, it works like I want. Therefore my next step is to figure out why it does not work in my "command" script. – zkirkland Aug 01 '16 at 18:41
  • @zachboy82 : Please update the question with your full script. – sjsam Aug 01 '16 at 18:54
  • 1
    `which` is much less accurate than `$BASH_SOURCE` -- it tells you what's first in the PATH, but that's not necessarily what was actually *invoked*. (`which` knows nothing about aliases, shell functions, cached lookups, etc; a use of it isn't better off replaced by a `type` invocation is rare, and in this particular use case `BASH_SOURCE` is even more appropriate than `type`). – Charles Duffy Aug 01 '16 at 19:10
  • @CharlesDuffy : Great note, will update shortly – sjsam Aug 01 '16 at 19:24