81

As far as I know, square brackets are used to enclose an expression usually in if else statements.

But I found square brackets being used without the "if" as follows:

[ -r /etc/profile.d/java.sh ] && . /etc/profile.d/java.sh

in the following script.

#!/bin/bash### BEGIN INIT INFO  
# Provides:          jbossas7  
# Required-Start:    $local_fs $remote_fs $network $syslog  
# Required-Stop:     $local_fs $remote_fs $network $syslog  
# Default-Start:     2 3 4 5  
# Default-Stop:      0 1 6  
# Short-Description: Start/Stop JBoss AS 7  
### END INIT INFO  
# chkconfig: 35 92 1  

## Include some script files in order to set and export environmental variables  
## as well as add the appropriate executables to $PATH.  
[ -r /etc/profile.d/java.sh ] && . /etc/profile.d/java.sh  
[ -r /etc/profile.d/jboss.sh ] && . /etc/profile.d/jboss.sh  

JBOSS_HOME=/sw/AS7  

AS7_OPTS="$AS7_OPTS -Dorg.apache.tomcat.util.http.ServerCookie.ALLOW_HTTP_SEPARATORS_IN_V0=true"   ## See AS7-1625  
AS7_OPTS="$AS7_OPTS -Djboss.bind.address.management=0.0.0.0"  
AS7_OPTS="$AS7_OPTS -Djboss.bind.address=0.0.0.0"  

case "$1" in  
    start)  
        echo "Starting JBoss AS 7..."  
        #sudo -u jboss sh ${JBOSS_HOME}/bin/standalone.sh $AS7_OPTS           ##  If running as user "jboss"  
        #start-stop-daemon --start --quiet --background --chuid jboss --exec ${JBOSS_HOME}/bin/standalone.sh $AS7_OPTS   ## Ubuntu  
        ${JBOSS_HOME}/bin/standalone.sh $AS7_OPTS &  
    ;;  
    stop)  
        echo "Stopping JBoss AS 7..."  
        #sudo -u jboss sh ${JBOSS_HOME}/bin/jboss-admin.sh --connect command=:shutdown            ##  If running as user "jboss"  
        #start-stop-daemon --start --quiet --background --chuid jboss --exec ${JBOSS_HOME}/bin/jboss-admin.sh -- --connect command=:shutdown     ## Ubuntu  
        ${JBOSS_HOME}/bin/jboss-cli.sh --connect command=:shutdown  
    ;;  
    *)  
        echo "Usage: /etc/init.d/jbossas7 {start|stop}"; exit 1;  
    ;;  
esac  

exit 0  

What do square brackets do without the "if"? I mean, exactly, what do they mean when used in that context?

This isn't a duplicate of that in which the OP used "if" which I don't have a problem with. In this question, brackets were used in a counter intuitive way. That question and this question may have the same answer but they are two different questions.

1
  • 17
    Not a duplicate. The other question asks about the if statement. This question asks what brackets mean without an if statement.
    – Mark Berry
    Jun 12, 2014 at 19:45

2 Answers 2

99

Square brackets are a shorthand notation for performing a conditional test. The brackets [, as well as [[ are actual commands within Unix, believe it or not.

Think:

$ [ -f /etc/rc.local ] && echo "real file"
real file

-and-

$ test -f /etc/rc.local && echo "real file"
real file

In Bash the [ is a builtin command as well as an executable. [[ is just a keyword to Bash.

Example

You can confirm this using type:

$ type -a [
[ is a shell builtin
[ is /usr/bin/[

$ type -a [[
[[ is a shell keyword

You can see the physical executable here:

$ ls -l /usr/bin/[
-rwxr-xr-x 1 root root 37000 Nov  3  2010 /usr/bin/[

builtins vs. keywords

If you take a look at the Bash man page, man bash, you'll find the following definitions for the 2:

  • keywords - Reserved words are words that have a special meaning to the shell. The following words are recognized as reserved when unquoted and either the first word of a simple command (see SHELL GRAMMAR below) or the third word of a case or for command:

    ! case  do done elif else esac fi for function if in select then until while { } time [[ ]]
    
  • builtins - If the command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, that function is invoked as described above in FUNCTIONS. If the name does not match a function, the shell searches for it in the list of shell builtins. If a match is found, that builtin is invoked.

    If the name is neither a shell function nor a builtin, and contains no slashes, bash searches each element of the PATH for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files (see hash under SHELL BUILTIN COMMANDS below). A full search of the directories in PATH is performed only if the command is not found in the hash table. If the search is unsuccessful, the shell searches for a defined shell function named command_not_found_handle. If that function exists, it is invoked with the original command and the original command's arguments as its arguments, and the function's exit status becomes the exit status of the shell. If that function is not defined, the shell prints an error message and returns an exit status of 127.

man page

If you look through the Bash man page you'll find the details on it.

test expr
[ expr ]
          Return a status of 0 or 1 depending on the evaluation of the 
          conditional expression expr.  Each operator and operand must be
          a separate argument.  Expressions are composed of the  primaries 
          described  above  under  CONDITIONAL EXPRESSIONS.   test does not 
          accept any options, nor does it accept and ignore an argument of 
          -- as signifying the end of options.

Lastly from the man page:

          test and [ evaluate conditional expressions using a set of rules
          based on the number of arguments.

EDIT #1

Follow-up question from the OP.

Ok, so why is there a need for an "if" then? I mean, why "if" even exists if "[" would suffice.

The if is part of a conditional. The test command or [ ... ] command simply evaluate the conditional, and return a 0 or a 1. The 0 or 1 is then acted on by the if statement. The 2 are working together when you use them.

Example

if [ ... ]; then
   ... do this ...
else 
   ... do that ...
fi
14
  • 3
    Ok, so why is there a need for an "if" then? I mean, why "if" even exists if "[" would suffice. Nov 7, 2013 at 8:26
  • 1
    Little nitpick: [[ may also be a shell builtin. Nov 7, 2013 at 14:45
  • 4
    @supertonsky - they work but they only return the status of the test, they can't act on it in any kind of way. The if acts like a switch and performs the commands in the then block or not depending on the results returned by the conditional. if isn't really optional in the way you're thinking, the examples we showed use && which is kind of like the if. If the conditional fails, then the command after the && aren't run.
    – slm
    Nov 7, 2013 at 17:42
  • 1
    @SteveKoch - as I understand it, the ] is an argument in this context to the command [. I'd guess that there are but I can't think of any off the top of my head. Might be worth posting it as another Q if you're truly curious.
    – slm
    Feb 7, 2015 at 1:31
  • 1
    @SteveKoch - incidentally, /usr/bin/[ shows as being part of the coreutils on my Fedora system. You can always consult the source on these matters if you want to know exactly how such things work. git.savannah.gnu.org/cgit/coreutils.git
    – slm
    Feb 7, 2015 at 1:39
34

Ooohh, one of my favorite topics!!

Square brackets are a synonym for the "test" command. If you read the test man page, you'll see that you can invoke the test command as either

test -r /etc/profile.d/java.sh

or

[ -r /etc/profile.d/java.sh ]

The spaces between the brackets and the stuff inside and outside them are required.

The "test" command in this case is checking to see if the file /etc/profile.d/java.sh is readable to the current user. Implied is a check to see if it exists, of course. :-)

The && is a bash syntax shortcut for "if the command on the left succeeds, then execute the command on the right. So, this compound command is a shorthand for an "if-then" that would look like this:

if test -r /etc/profile.d/java.sh
then
  /etc/profile.d/java.sh
fi

Now, you'll also find double square brackets explained in the bash man page. Those are a bash internal version of an extended testing function. Be aware that those are not exactly the same. There are things you can do with those that you cannot do with the "test" command and its "[" synonym.

3
  • 1
    Just want to make sure I understand. If square brackets are an alias for "test", shouldn't your second example be "[ -r /etc/profile.d/java.sh ]" ? In other words, remove the redundant test statement.
    – pmont
    Mar 6, 2015 at 16:47
  • Yes, pmont, you're exactly right, of course! I wasn't careful when I cut and pasted. I've fixed it. Thanks!
    – Mike Diehn
    May 21, 2015 at 3:57
  • Just in case, a=("$( which [; )" "$( which test; )"); ls -la "${a[@]}"; type [ test [[;.
    – Artfaith
    Jun 13, 2022 at 18:24

Not the answer you're looking for? Browse other questions tagged .