Trying to understand this piece of code:

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

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


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.

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!"

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

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:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.