3

I'm new to Shell Scripting:

I'm trying to create a script that asks for user input as to the folder name, finds the directory the script is being run from, and creates a folder within that same directory with a bunch of files (I can do that part)

My issue is I can't seem to figure out how to make the script find its current directory without explicitly spelling it out.

I want to be able to run it from anywhere and have it create the folder right next to it without the user having to path it from the home folder every time.

Could someone help with this?

2 Answers2

3

You could try this one liner:

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

Will leave you with a $DIR variable that contains the full path to the current directory. See this answer for more information!

Community
  • 1
  • 1
binaryatrocity
  • 956
  • 5
  • 10
0
script_dir=$(dirname "$0")

$0 is the name of the running script, as entered on the command line (for example: ./bin/script)

If you want the full path:

script_dir=$(cd -P -- "$(dirname "$0")" && pwd -P)
glenn jackman
  • 238,783
  • 38
  • 220
  • 352