Replacement for source in sh

BashShellShDot Source

Bash Problem Overview


I need to set the environment variables, usually we do this by

source script.sh

But now, I am automating it during the boot process and it looks like the root boots by default with sh shell. How do I source this script in sh?

Bash Solutions


Solution 1 - Bash

The dot command '.' is the equivalent of the C Shell (and Bash) source command. It is specified by POSIX (see dot), and supported by the Bourne and Korn shells (and zsh, I believe).

. somefile

Note that the shell looks for the file using $PATH, but the file only has to be readable, not executable.

As noted in the comments below, you can of course specify a relative or absolute pathname for the file — any name containing a slash will not be searched for using $PATH. So:

. /some/where/somefile
. some/where/somefile
. ./somefile

could all be used to find somefile if it existed in the three different specified locations (if you could replace . with ls -l and see a file listed).

Pedants of the world unite! Yes, if the current directory is the root directory, then /some/where/somefile and ./some/where/somefile would refer to the same file — with the same real path — even without links, symbolic or hard, playing a role (and so would ../../some/where/somefile).

Solution 2 - Bash

tl;dr With sh (as opposed to bash) the argument must contain a slash: source ./script.sh, not just source script.sh. Unless script.sh can be found in PATH.

Dot (.) command exists in both bash and sh. Additionally, bash aliases it as source. From bash manual:

https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html#index-source

> source > > source filename > > A synonym for . (see Bourne Shell Builtins).

https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#index-_002e

> . (a period) > > . filename [arguments] > > Read and execute commands from the filename argument in the current shell context. If filename does not contain a slash, the PATH variable is used to find filename. When Bash is not in POSIX mode, the current directory is searched if filename is not found in $PATH.

From POSIX:

> If file does not contain a /, the shell shall use the search path specified by PATH to find the directory containing file. Unlike normal command search, however, the file searched for by the dot utility need not be executable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvkrisView Question on Stackoverflow
Solution 1 - BashJonathan LefflerView Answer on Stackoverflow
Solution 2 - Bashx-yuriView Answer on Stackoverflow