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.

slm
  • 369,824
supertonsky
  • 913
  • 1
  • 7
  • 6
  • 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 '14 at 19:45

2 Answers2

101

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
slm
  • 369,824
  • 3
    Ok, so why is there a need for an "if" then? I mean, why "if" even exists if "[" would suffice. – supertonsky Nov 07 '13 at 08:26
  • @supertonsky - see updates, let me know if that makes sense. – slm Nov 07 '13 at 12:44
  • 1
    Little nitpick: [[ may also be a shell builtin. – helpermethod Nov 07 '13 at 14:45
  • @helpermethod - I said that: "In Bash the [ is a builtin command as well as an executable. So is [[" – slm Nov 07 '13 at 14:47
  • @slm Sry, only read the first part. – helpermethod Nov 07 '13 at 15:08
  • Is "if" just optional? When is it required? It seems test or "[" command works even without the "if", so why use "if"? Readability? – supertonsky Nov 07 '13 at 16:39
  • 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 07 '13 at 17:42
  • [ is both a Bash shell builtin and an external command. [[ is only a builtin; in fact type [[ says it's a "shell keyword", unlike [ which is a "shell builtin". (I'm not sure what the real distinction is, though; it seems to be usable as if it were a command.) – Keith Thompson Nov 08 '13 at 01:29
  • @KeithThompson - builtins just means that they're provided by the shell. I've re-worked that section since you're the 2nd person today that was confused by my sentence. Let me know if it's clearer. Thanks for the feedback! – slm Nov 08 '13 at 01:34
  • This is a very clear answer and helped me out. In my case I learned that [ -e FILE checks if FILE exists. Just curious, though, what about the trailing ]? It's obvious that it ends the [ arguments and looks nice, but why? Are there any other bash commands that require a trailing character as the last argument? – Steve Koch Feb 06 '15 at 21:52
  • 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 07 '15 at 01: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. http://git.savannah.gnu.org/cgit/coreutils.git – slm Feb 07 '15 at 01:39
  • @slm I am curious but not sure how to ask the question. I'm guessing my curiosity is just fueled by unfamiliarity, not anything important. Following your link, I did find the code which checks for the trailing bracket towards the end of test.c file: if (margc < 2 || !STREQ (margv[margc - 1], "]")). For what it's worth, I searched for "\!STREQ (margv\[margc - 1\]" and didn't find any of the other coreutils functions checking the last argument in that fashion. – Steve Koch Feb 10 '15 at 00:28
  • @SteveKoch - cool! That's a good data point that there aren't any other cmds besides [. – slm Feb 10 '15 at 01:37
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.

Mike Diehn
  • 1,008
  • 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 06 '15 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 '15 at 03:57
  • Just in case, a=("$( which [; )" "$( which test; )"); ls -la "${a[@]}"; type [ test [[;. – Artfaith Jun 13 '22 at 18:24