Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 296
Bart van Heukelom Avatar asked May 24 '12 10:05

Bart van Heukelom


People also ask

How do you check if a file exists in a directory bash?

Check if Directory Exist The operators -d allows you to test whether a file is a directory or not. [ -d /etc/docker ] && echo "$FILE is a directory." You can also use the double brackets [[ instead of a single one [ .

How do you source a file in shell?

A file is sourced in two ways. One is either writting as source <fileName> or other is writting as . ./<filename> in the command line. When a file is sourced, the code lines are executed as if they were printed on the command line.

What is source command in bash?

The source command reads and executes commands from the file specified as its argument in the current shell environment. It is useful to load functions, variables, and configuration files into shell scripts. source is a shell built-in in Bash and other popular shells used in Linux and UNIX operating systems.


1 Answers

Is defining your own version of @include an option?

include () {     [[ -f "$1" ]] && source "$1" }  include FILE 
like image 94
chepner Avatar answered Sep 26 '22 06:09

chepner