简体   繁体   中英

Understand when to use spaces in bash scripts

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.

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 '' ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM