basherror-handlinginclude

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


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

Solution

  • The best way to avoid repetition is to use the special variable $_ (= the last argument of the previous command):

    test -f /path/to/some/file && source "$_"
    

    The post How can I recall the argument of the previous bash command? has lots of interesting details on those special "recalled" variables.

    The double-quotes are necessary if the path has spaces in it:

    $ echo 'echo hello' > filename\ with\ spaces
    $ ls 
    'filename with spaces'
    $ test -f "filename with spaces" && source $_
    -bash: filename: No such file or directory
    $ test -f "filename with spaces" && source "$_"
    hello