Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script current directory?

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

like image 500
Suzan Cioc Avatar asked Mar 27 '12 12:03

Suzan Cioc


People also ask

How do I get the current directory in a .sh file?

You can use built-in shell command pwd or shell variable $PWD to get current working directory as per your requirement.

How do I find my current directory name in shell?

pwd (print working directory) – The pwd command is used to display the name of the current working directory in the Linux system using the terminal. This is a shell building command that is available in most Unix shells such as Bourne shell, ash, bash, kash, and zsh.

How do I get current working directory in bash?

Print Current Working Directory ( pwd ) To print the name of the current working directory, use the command pwd . As this is the first command that you have executed in Bash in this session, the result of the pwd is the full path to your home directory.

What is working directory in shell script?

The current working directory is the directory in which the user is currently working in. Each time you interact with your command prompt, you are working within a directory. By default, when you log into your Linux system, your current working directory is set to your home directory.


2 Answers

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}" 

You're weclome

like image 159
krg Avatar answered Sep 20 '22 06:09

krg


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"

like image 32
saada Avatar answered Sep 23 '22 06:09

saada