Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of square brackets in shell scripts

Tags:

unix

sh

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?

like image 342
runtimeZero Avatar asked Nov 06 '15 14:11

runtimeZero


People also ask

What is a square bracket used for?

Square brackets, often just called brackets in American English, are a set of punctuation marks that are most often used to alter or add information to quoted material. Square brackets come in pairs as [ and ].

What are [] in bash?

[[ … ]] double brackets are an alternate form of conditional expressions in ksh/bash/zsh with a few additional features, for example you can write [[ -L $file && -f $file ]] to test if a file is a symbolic link to a regular file whereas single brackets require [ -L "$file" ] && [ -f "$file" ] .

What is double square brackets in shell script?

The double brackets, [[ ]], were introduced in the Korn Shell as an enhancement that makes it easier to use in tests in shell scripts. We can think of it as a convenient alternative to single brackets. It's available in many shells like Bash and zsh.

What does square brackets mean in syntax?

mvBASIC Syntax NotationsAnything shown enclosed within square brackets is optional unless indicated otherwise. The square brackets themselves are not typed unless they are shown in bold. | A vertical bar that separates two or more elements indicates that any one of the elements can be typed.


1 Answers

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.

like image 97
Noufal Ibrahim Avatar answered Sep 30 '22 18:09

Noufal Ibrahim