23

Trying to understand this piece of code:

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

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

Eric Hodgins
  • 357
  • 1
  • 2
  • 6

2 Answers2

27

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:

Sergiy Kolodyazhnyy
  • 16,187
  • 11
  • 53
  • 104
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,582
  • 5
  • 48
  • 75
  • 1
    -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