Get current directory and concatenate a path - shell

This is a shell script (.sh file). I need to create an absolute path based on the current directory. I know about pwd, but how do I concatenate it with another string? Here is an example of what I am trying to do:
"$pwd/some/path"

Sounds like you want:
path="$(pwd)/some/path"
The $( opens a subshell (and the ) closes it) where the contents are executed as a script so any outputs are put in that location in the string.
More useful often is getting the directory of the script that is running:
dot="$(cd "$(dirname "$0")"; pwd)"
path="$dot/some/path"
That's more useful because it resolves to the same path no matter where you are when you run the script:
> pwd
~
> ./my_project/my_script.sh
~/my_project/some/path
rather than:
> pwd
~
> ./my_project/my_script.sh
~/some/path
> cd my_project
> pwd
~/my_project
> ./my_script.sh
~/my_project/some/path
More complex but if you need the directory of the current script running if it has been executed through a symlink (common when installing scripts through homebrew for example) then you need to parse and follow the symlink:
if [[ "$OSTYPE" == *darwin* ]]; then
READLINK_CMD='greadlink'
else
READLINK_CMD='readlink'
fi
dot="$(cd "$(dirname "$([ -L "$0" ] && $READLINK_CMD -f "$0" || echo "$0")")"; pwd)"
More complex and more requirements for it to work (e.g. having a gnu compatible readlink installed) so I tend not to use it as much. Only when I'm certain I need it, like installing a command through homebrew.

Using the shell builtin pwd in a command substitution ($(...)) is an option, but not necessary, because all POSIX-compatible shells define the special $PWD shell variable that contains the current directory as an absolute path, as mandated by POSIX.
Thus, using $PWD is both simpler and more efficient than $(pwd):
"$PWD/some/path" # alternatively, for visual clarity: "${PWD}/some/path"
However, if you wanted to resolve symlinks in the directory path, you DO need pwd, with its -P option:
"$(pwd -P)/some/path"
Note that POSIX mandates that $PWD contain an absolute pathname with symlinks resolved.
In practice, however, NO major POSIX-like shell (bash, dash, ksh, zsh) does that - they all retain symbolic link components. Thus, the (POSIX-compliant) pwd -P is needed to resolve them.
Note that all said POSIX-like shells implement pwd as a builtin that supports -P.
Michael Allen's helpful answer points out that it's common to want to know the directory of where the running script is located.
The challenge is that the script file itself may be a symlink, so determining the true directory of origin is non-trivial, especially when portability is a must.
This answer (of mine) shows a solution.

wd=`pwd`
new_path="$wd/some/path"

with "dirname $0" you can get dynamin path upto current run scipt.
for example : your file is locateted in shell folder file name is xyz and there are anthor file abc to include in xyz file.
so put in xyz file LIke:
php "`dirname $0`"/abc.php

Related

In bash, what's the best way for a script to reference the path of another script?

scripts/a.sh calls scripts/b.sh through source or through sh.
But I cannot be sure that the working directory will be scripts or the parent of scripts or something else.
What is the best practice for referencing b.sh? I can find the directory of the current script, then cd to that directory, and then simply call ./b.sh. But that seems like a lot of code to put into every script that calls another.
There is no need for a cd, cause source or command take a full path. Just get the dir name of the full path of your script and run the script from there.
From bash manual:
0
($0) Expands to the name of the shell or shell script. ....
From man readlink:
-f, --canonicalize
canonicalize by following every symlink in every component of the given name recursively; ...
From man dirname:
dirname - strip non-directory suffix from file name
Altogether:
. "$(dirname "$(readlink -f "$0")")"/b.sh
I've seen some bash scripts that start with something similar to:
DIR=$(dirname "$(readlink -f "$0")")
cd "$DIR"
So the current working directory in a script stays the same, even if user runs it from another directory.
#edit
Like #GordonDavisson suggested in comments, we can also add your dir to PATH:
export PATH="$(dirname "$(readlink -f "$0")")":"$PATH"
Then running:
. a.sh
will search for a.sh script through inside directories listed in PATH variable, which it will find in the first dir.

Bash: Path to symlink which calls this script

I have the following situation:
I have a script with a path of: /usr/local/bin/rsnapshot.period
I want to have symlinks to it in various /etc/cron.[period]/ directories, like /etc/cron.hourly/rsnapshot
I'd like to have the script look up the full path to the symlink, and pull out the [period] part, so I can feed it to rsnapshot.
I can do all the text hacking. The problem I'm having trouble with is getting the path to the calling symlink from within the bash script. $0 seems to point to /usr/local/bin/rsnapshot.period
Is there a better way to get this info?
$0 seems to point to /usr/local/bin/rsnapshot.period
$0 is set by the calling program in its exec*() call, as the first word of the arg argument or the first element of the argv argument. If you feel that the tool you're using is setting this value incorrectly then you should open a bug with the developer.
In the meantime, using a hardlink instead of a symlink will allow you to detect the script name properly, but will break if you aren't careful with the tool you use to edit the main script.
Turns out my problem wasn't that $0 was incorrect - it was pointing to the right place. However, as I was trying to get the absolute path of it, I was using 'realpath' before it, which resolved symlinks.
Passing realpath the '-s' fixed it. Here's my test script and the output of it:
Script:
#!/bin/sh
echo \$0: $0
echo realpath -s \$0: $(realpath -s $0)
echo readlink -e: $(readlink -e $0)
Executed:
$0: ./rsnapshot
realpath -s $0: /etc/cron.hourly/rsnapshot
readlink -e: /usr/local/bin/rsnapshot.period

How do I change Korn(ksh) version dynamically based on platform?

I wanted to use the /usr/bin/ksh93 interpreter on AIX and Linux wherever possible but switch to /usr/bin/ksh where it's not applicable like Mac OS X and wanted the script to be universally compatible in unix. I don't think there is any fallback mechanism in shebang
Since ksh and sh have some syntax in common, you can prefix the start of the
script with a test for ksh or ksh93 in the PATH and rerun the script with
the right interpreter. Replace the #! with the pathname to sh. (Hopefully
it is the same on both machines, or you are back where you started. You can
still try #!/usr/bin/env sh if your env will find the path for you). Add:
#!/bin/sh
if [ "$DONEIT" != true ]
then export DONEIT=true # avoid recursion
if command -v ksh > /dev/null 2>&1
then exec ksh $0 "$#"
else exec ksh93 $0 "$#"
fi
fi
... rest of your script ...
Note: command -v is the POSIX way for finding a command's path.
(Often in these situations, at the installation of a package a script goes
through the #! files and updates the interpreter path to that needed by the
target machine).
Alternatively, you could replace the #! line by any fixed path you control, eg #!/home/user/myksh, and link that file to the right ksh.
You can make a symbolic links.
if [ -f /usr/bin/ksh93 ]; then
ln -s /usr/bin/ksh93 /usr/bin/localksh
else
ln -s /usr/bin/ksh /usr/bin/localksh
fi
The shebang will be #!/usr/bin/localksh.
I would prefer using a normal shebang #!/bin/ksh, but when that one already exists and is the wrong version you will be stuck.

Relative paths based on file location instead of current working directory [duplicate]

This question already has answers here:
How do I get the directory where a Bash script is located from within the script itself?
(74 answers)
Closed 8 years ago.
Given:
some.txt
dir
|-cat.sh
With cat.sh having the content:
cat ../some.txt
Then running ./cat.sh inside dir works fine while running ./dir/cat.sh on the same level as dir does not. I expect this to be due to the different working directories. Is there an easy way to make the path ../some.txt relative to the location of cat.sh?
What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.
#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.
Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)
#Martin Konecny's answer provides an effective solution, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.
This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:
Linux / GNU readlink solution:
If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:
scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")
Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.
Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):
If your script must run on any platform that:
has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.
macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, #Charles Duffy).
The following solution, inspired by https://stackoverflow.com/a/1116890/45375,
defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.
Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.
If readlink is available, it is used (without options) - true on most modern platforms.
Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
(Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., #Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)
An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.
If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.
#!/usr/bin/env bash
# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...
local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH=
# Since we'll be using `command` below for a predictable execution
# environment, we make sure that it has its original meaning.
{ \unalias command; \unset -f command; } &>/dev/null
while :; do # Resolve potential symlinks until the ultimate target is found.
[[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
if [[ -L $fname ]]; then
# Extract [next] target path, which is defined
# relative to the symlink's own directory.
if [[ -n $readlinkexe ]]; then # Use `readlink`.
target=$("$readlinkexe" -- "$fname")
else # `readlink` utility not available.
# Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant
# way to determine a symlink's target. Hypothetically, this can break with
# filenames containig literal ' -> ' and embedded newlines.
target=$(command ls -l -- "$fname")
target=${target#* -> }
fi
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we
# have a normalized path.
if [[ $fname == '.' ]]; then
command printf '%s\n' "${targetDir%/}"
elif [[ $fname == '..' ]]; then
# Caveat: something like /var/.. will resolve to /private (assuming
# /var# -> /private/var), i.e. the '..' is applied AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")
Just one line will be OK.
cat "`dirname $0`"/../some.txt

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

I'm writing a Bash script. I need the current working directory to always be the directory that the script is located in.
The default behavior is that the current working directory in the script is that of the shell from which I run it, but I do not want this behavior.
#!/bin/bash
cd "$(dirname "$0")"
The following also works:
cd "${0%/*}"
The syntax is thoroughly described in this StackOverflow answer.
Try the following simple one-liners:
For all UNIX/OSX/Linux
dir="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"
Bash
dir="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
Note: A double dash (--) is used in commands to signify the end of command options, so files containing dashes or other special characters won't break the command.
Note: In Bash, use ${BASH_SOURCE[0]} in favor of $0, otherwise the path can break when sourcing it (source/.).
*For Linux, Mac and other BSD:
cd "$(dirname "$(realpath -- "$0")")";
Note: realpath should be installed in the most popular Linux distribution by default (like Ubuntu), but in some it can be missing, so you have to install it.
Note: If you're using Bash, use ${BASH_SOURCE[0]} in favor of $0, otherwise the path can break when sourcing it (source/.).
Otherwise you could try something like that (it will use the first existing tool):
cd "$(dirname "$(readlink -f -- "$0" || realpath -- "$0")")"
For Linux specific:
cd "$(dirname "$(readlink -f -- "$0")")"
*Using GNU readlink on BSD/Mac:
cd "$(dirname "$(greadlink -f -- "$0")")"
Note: You need to have coreutils installed
(e.g. 1. Install Homebrew, 2. brew install coreutils).
In bash
In bash you can use Parameter Expansions to achieve that, like:
cd "${0%/*}"
but it doesn't work if the script is run from the same directory.
Alternatively you can define the following function in bash:
realpath () {
[[ "$1" = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
This function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWD variable + filename argument (without ./ prefix).
or here is the version taken from Debian .bashrc file:
function realpath()
{
f=$#
if [ -d "$f" ]; then
base=""
dir="$f"
else
base="/$(basename -- "$f")"
dir="$(dirname -- "$f")"
fi
dir="$(cd -- "$dir" && /bin/pwd)"
echo "$dir$base"
}
Related:
How to detect the current directory in which I run my shell script?
How do I get the directory where a Bash script is located from within the script itself?
Bash script absolute path with OS X
Reliable way for a Bash script to get the full path to itself
See also:
How can I get the behavior of GNU's readlink -f on a Mac?
cd "$(dirname "${BASH_SOURCE[0]}")"
It's easy. It works.
The accepted answer works well for scripts that have not been symlinked elsewhere, such as into $PATH.
#!/bin/bash
cd "$(dirname "$0")"
However if the script is run via a symlink,
ln -sv ~/project/script.sh ~/bin/;
~/bin/script.sh
This will cd into the ~/bin/ directory and not the ~/project/ directory, which will probably break your script if the purpose of the cd is to include dependencies relative to ~/project/
The symlink safe answer is below:
#!/bin/bash
cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" # cd current directory
readlink -f is required to resolve the absolute path of the potentially symlinked file.
The quotes are required to support filepaths that could potentially contain whitespace (bad practice, but its not safe to assume this won't be the case)
This script seems to work for me:
#!/bin/bash
mypath=`realpath $0`
cd `dirname $mypath`
pwd
The pwd command line echoes the location of the script as the current working directory no matter where I run it from.
There are a lot of correct answers in here, but one that tends to be more useful for me (making sure a script's relative paths remain predictable/work) is to use pushd/popd:
pushd "$(dirname ${BASH_SOURCE:0})"
trap popd EXIT
# ./xyz, etc...
This will push the source file's directory on to a navigation stack, thereby changing the working directory, but then, when the script exits (for whatever reason, including failure), the trap will run popd, restoring the current working directory before it was executed. If the script were to cd and then fail, your terminal could be left in an unpredictable state after the execution ends - the trap prevents this.
I take this and it works.
#!/bin/bash
cd "$(dirname "$0")"
CUR_DIR=$(pwd)
Get the real path to your script
if [ -L $0 ] ; then
ME=$(readlink $0)
else
ME=$0
fi
DIR=$(dirname $ME)
(This is answer to the same my question here: Get the name of the directory where a script is executed)
cd "`dirname $(readlink -f ${0})`"
Most answers either don't handle files which are symlinked via a relative path, aren't one-liners or don't handle BSD (Mac). A solution which does all three is:
HERE=$(cd "$(dirname "$BASH_SOURCE")"; cd -P "$(dirname "$(readlink "$BASH_SOURCE" || echo .)")"; pwd)
First, cd to bash's conception of the script's directory. Then readlink the file to see if it is a symlink (relative or otherwise), and if so, cd to that directory. If not, cd to the current directory (necessary to keep things a one-liner). Then echo the current directory via pwd.
You could add -- to the arguments of cd and readlink to avoid issues of directories named like options, but I don't bother for most purposes.
You can see the full explanation with illustrations here:
https://www.binaryphile.com/bash/2020/01/12/determining-the-location-of-your-script-in-bash.html
echo $PWD
PWD is an environment variable.
If you just need to print present working directory then you can follow this.
$ vim test
#!/bin/bash
pwd
:wq to save the test file.
Give execute permission:
chmod u+x test
Then execute the script by ./test then you can see the present working directory.

Resources