What is the most concise way to source a file (only if it exists) in Bash?

16,081

Solution 1

Is defining your own version of @include an option?

include () {
    [[ -f "$1" ]] && source "$1"
}

include FILE

Solution 2

If you're concerned about a one-liner without repeating the filename, perhaps:

FILE=/path/to/some/file && test -f $FILE && source $FILE

Solution 3

If you are concerned about warning (and lack of existence of sourced file isn't critical for your script) just get rid of the warning:

source FILE 2> /dev/null

Solution 4

If you want to always get a clean exit code, and continue no matter what, then you can do:

source ~/.bashrc || true && echo 'is always executed!'

And if you also want to get rid of the error message then:

source ~/.bashrc 2> /dev/null || true && echo 'is always executed!'

Solution 5

You could try

test -f $FILE && source $FILE

If test returns false, the second part of && is not evaluated

Share:
16,081
Bart van Heukelom
Author by

Bart van Heukelom

Professional software developer, online games, full stack but mostly backend. Electronics tinkerer. Maker. Freelance. See LinkedIn for more details. My UUID is 96940759-b98b-4673-b573-6aa6e38272c0

Updated on July 05, 2022

Comments

  • Bart van Heukelom
    Bart van Heukelom almost 2 years

    In Bash scripting, is there a single statement alternative for this?

    if [ -f /path/to/some/file ]; then
        source /path/to/some/file
    fi
    

    The most important thing is that the filename is there only once, without making it a variable (which adds even more lines).

    For example, in PHP you could do it like this

    @include("/path/to/some/file"); // @ makes it ignore errors