Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

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.

share|improve this question

marked as duplicate by jasonwryan, slm, Anthon, Bernhard, Thomas Nyman Nov 7 '13 at 22:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
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 at 19:45

2 Answers 2

up vote 4 down vote accepted

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
share|improve this answer
    
Ok, so why is there a need for an "if" then? I mean, why "if" even exists if "[" would suffice. –  supertonsky Nov 7 '13 at 8:26
    
@supertonsky - see updates, let me know if that makes sense. –  slm Nov 7 '13 at 12:44
1  
Little nitpick: [[ may also be a shell builtin. –  helpermethod Nov 7 '13 at 14:45
    
@helpermethod - I said that: "In Bash the [ is a builtin command as well as an executable. So is [[" –  slm Nov 7 '13 at 14:47
1  
@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 '13 at 17:42

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

[ test -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 bash shortcut for "if the command on the left succeeds, then execute the command on the right. So, this compound command it a shorthand for and 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 can do with the "test" command and it's "[" synonym.

share|improve this answer
    
+1 for explaining && –  supertonsky Nov 7 '13 at 8:28

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