What is current directory of shell script? I this current directory from which I called it? Or this directory where script located?
You can use built-in shell command pwd or shell variable $PWD to get current working directory as per your requirement.
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.
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.
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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With