runtimeZero
runtimeZero

Reputation: 28046

Purpose of square brackets in shell scripts

I came across this line in one of the shell scripts:

[-f $host_something ] && .$host_something

What are the square brackets with the -f switch supposed to do, and what is the point of ANDing it with the same environment variable?

Upvotes: 8

Views: 4024

Answers (3)

Walter A
Walter A

Reputation: 19982

You need some more spaces.
The command

[ -f $host_something ] && . $host_something

stands for

if [ -f $host_something ]; then
   source $host_something
fi

or in words:
When the file given in the variable host_something really is a file, then execute the lines in that file without opening a subshell. You do not want a subshell, since all the settings in the subshell get lost as soon as the subshell is finished.

Upvotes: 2

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72745

The [ is actually an actual binary. It's an alias for the test(1) command. It will ignore it's last argument which should be ]. Run man test for further information. It's not really shell syntax.

Upvotes: 5

Woodrow Douglass
Woodrow Douglass

Reputation: 2655

The square bracket is really an alias for the test tool, so you can look at man test to find out how it works. the -f switch is one of many tests that can be run by this tool, and tests if a file exists and is a regular file.

Upvotes: 2

Related Questions