Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand when to use spaces in bash scripts

Tags:

linux

bash

unix

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.

like image 283
user584583 Avatar asked Jul 31 '26 11:07

user584583


1 Answers

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

like image 174
Igor Chubin Avatar answered Aug 02 '26 04:08

Igor Chubin