Shell Script Current Directory

Shell script current directory?

The current(initial) directory of shell script is the directory from which you have called the script.

How do I get the directory where a Bash script is located from within the script itself?


#!/usr/bin/env bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.

It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:

#!/usr/bin/env bash

SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
SOURCE=$(readlink "$SOURCE")
[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )

This last one will work with any combination of aliases, source, bash -c, symlinks, etc.

Beware: if you cd to a different directory before running this snippet, the result may be incorrect!

Also, watch out for $CDPATH gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2 on Mac). Adding >/dev/null 2>&1 at the end of your cd command will take care of both possibilities.

To understand how it works, try running this more verbose form:

#!/usr/bin/env bash

SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET=$(readlink "$SOURCE")
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE=$TARGET
else
DIR=$( dirname "$SOURCE" )
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR=$( dirname "$SOURCE" )
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"

And it will print something like:

SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'

Unix shell script find out which directory the script file resides?

In Bash, you should get what you need like this:

#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

How can I set the current working directory to the directory of the script in Bash?


#!/bin/bash
cd "$(dirname "$0")"

Bash - Get Current Directory or Folder Name (Without Full Path) In Bash Script

No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion:

result=${PWD##*/}          # to assign to a variable
result=${result:-/} # to correct for the case where PWD=/

printf '%s\n' "${PWD##*/}" # to print to stdout
# ...more robust than echo for unusual names
# (consider a directory named -e or -n)

printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
# ...useful to make hidden characters readable.

Note that if you're applying this technique in other circumstances (not PWD, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's extglob support to work even with multiple trailing slashes:

dirname=/path/to/somewhere//
shopt -s extglob # enable +(...) glob syntax
result=${dirname%%+(/)} # trim however many trailing slashes exist
result=${result##*/} # remove everything before the last / that still remains
result=${result:-/} # correct for dirname=/ case
printf '%s\n' "$result"

Alternatively, without extglob:

dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
result=${result:-/} # correct for dirname=/ case

Refer to the current directory in a shell script

If both the scripts are in the same directory and you got the ./foo.sh: No such file or directory error then the most likely cause is that you ran the first script from a different directory than the one where they are located in. Put the following in your first script so that the call to foo.sh works irrespective of where you call the first script from:

my_dir=`dirname $0`
#Call the other script
$my_dir/foo.sh

How to change current directory via shell script and execute command there?

This is very nearly a duplicate of Change the current directory from a Bash script, and the answer is very similar -- the only difference being the appending of the command you want to run.

Don't use a script at all; instead, in your ~/.bashrc or similar, define a function:

runInMyDir() {
cd ~/my-dir || return
runall
}

...to define a command runInMyDir. (If you want runall to happen in the background, add a & at the end of that line).


If you do want a script, that script needs to be sourced rather than executed out-of-process -- when a program is executed as an executable external to the shell, it has already been split off from the original shell before it starts, so it has no opportunity to change that shell's behavior. Thus, if you created a file named runInMyDir with the commands cd ~/my-dir || return and runall, you would need to run source runInMyDir rather than just runInMyDir to invoke it.

Current Directory in Shell Script

You could use:

mkdir -p build/iphoneos/$(basename $PWD).txt

or

mkdir -p build/iphoneos/${PWD##*/}.txt

The first calls the basename binary. The second one removes all character up to the last / character.

getting current directory in linux for argument

PWD variable does exactly what you want.
So just replace pwd with $PWD and you are done



Related Topics



Leave a reply



Submit