29

Trying to understand this piece of code:

if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

I'm not sure what the -f means exactly.

2 Answers2

31

In short, the piece of code will source /etc/bashrc file if it exists, and the existence is verified by [ command to which -f is an operator/parameter.

if...then...else...fi statement in shell scripting evaluates exit status of commands - 0 on success. So it's proper to do something like this:

if ping -c 4 google.com; then
    echo "We have a connection!"
fi

The command, in your case, is [ which is also known as test command. So it'd be perfectly valid to do

if test -f /etc/bashrc; then
    . /etc/bashrc
fi

The -f flag verifies two things: the provided path exists and is a regular file. If /etc/bashrc is in fact a directory or missing, test should return non-zero exit status to signal failure

This command originally was a separate command, that is not part of shell's built-in commands. Nowadays, most Bourne-like shells have it as built-in, and that's what shell will use.

On a side note, the /etc/bashrc seems like unnecessary extra file that your admin or original author of the code snippet is using. There exists /etc/bash.bashrc, which is intended as system-wide rc-file for bash, so one would expect that to be used.

See also:

14

The relevant man page to check for this is that of the shell itself, bash, because -f is functionality that the shell provides, it's a bash built-in.

On my system (CentOS 7), the fine man page covers it. The grep may not give the same results on other distributions. Nevertheless, if you run man bash and then search for '-f' it should give the results you require.

$ man bash | grep -A1 '\-f file$'
       -f file
              True if file exists and is a regular file.
$
steve
  • 21,892
  • 2
    -1 This answer is very misleading, following on from the question’s misleading title. -f has nothing to do with if; it is an option for the [ command, which just happens to be called using an if statement here. Also, it just so happens that [ (along with if) is built in to bash. – Brian Drake Mar 26 '22 at 12:48
  • Yeah, agree that this is a terrible answer. If you run man [ in a linux terminal, you'll see that -f is an option of the [ operator. From there it's apparent what -f does. – Drew Daniels Oct 04 '23 at 16:35