2

I wanted to run a simple bash timer and found this online (user brent7890)

#!/usr/bin/bash
timer=60
until [ "$timer" = 0 ]
do
clear
echo "$timer"
timer=`expr $timer - 1`
sleep 1
done
echo "-------Time to go home--------"

I couldn't copy and paste this code because the server is on another network. I typed it like this (below) and got an error on the line that starts with "until".

#!/usr/bin/bash
timer=60

#Note I forgot the space between [ and "
until ["$timer" = 0 ]

do
clear
echo "$timer"
timer=`expr $timer - 1`
sleep 1
done
echo "-------Time to go home--------"

Where is spacing like this documented? It seems strange that it matters. Bash scripts can be confusing, I want to understand why the space is important.

user584583
  • 1,242
  • 4
  • 18
  • 35
  • The confusion behind this question is the primary reason many style guided recommend completely avoiding `[`. Instead of `until [ "$timer" = 0 ]`, write `until test "$timer" = 0` and the need for spacing becomes obvious. – William Pursell Jan 09 '14 at 12:56
  • In contrast to spaces being required in a `[` (aka `test`) command, they're forbidden in an assignment. `timer=60` works, but `timer = 60` will try to run the `timer` command with the arguments "=" and "60". The lack of spaces is actually how the shell distinguishes an assignment from a regular command. Also, spaces are required around the operators in a `[` command: `[ "$timer"=0 ]` is a valid `test` command, but it doesn't do what you expect because it doesn't recognize `=` as an operator. – Gordon Davisson Jan 09 '14 at 15:49

1 Answers1

8

There are several rules, two basic of that are these:

  • You must separate all arguments of a command with spaces.
  • You must separate a command and the argument, that follows after, with a space.

[ here is a command (test).

If you write ["$timer" that means that you start command [60, and that is, of course, incorrect. The name of the command is [.

The name of the command is always separated from the rest of the command line with a space. (you can have a command with a space in it, but in this case you must write the name of the command in "" or '').

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
  • 1
    OK, [ is a synonym for the test command. http://stackoverflow.com/questions/8934012/when-square-brackets-are-required-in-bash-if-statement – user584583 Jan 09 '14 at 12:53