Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash semicolon being equal to newline is not exactly true?

Tags:

bash

shell

I've read in multiple articles that semicolon(;) in UNIX-like shells is equal to a new line.
However, the following is confusing me and I'm having no luck googling it either.

I'm guessing it's an issue with do in shell, but "bash semicolon do" is not exactly the most google-friendly search term combination.

Below is a simple for statement.

for i in {1..10}
do
echo "hi"
echo "bye"
done

As many Stack Overflow gurus have posted, every newline can be substituted with semicolons.

So.. we have this following "same" statement.

for i in {1..10}; do; echo "hi"; echo "bye"; done

and we get:

-bash: syntax error near unexpected token `;'

What exactly is the semicolon? Is this just an unique issue with do?

like image 269
Gyuhyeon Lee Avatar asked Jun 26 '18 02:06

Gyuhyeon Lee


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

Do bash scripts use semicolons?

Double semicolon is required for a bash syntax to correctly parse the command.

What does $() mean in bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

What is newline character in bash?

The newline character is denoted as “\n”. Using both the echo and printf commands, we can print strings with new lines in them.


1 Answers

Looking at the syntax of the for/do loop,

for name [ [in [words …] ] ; ] do commands; done

we can see that do is followed by commands immediately, so using a newline after do doesn't replace a semicolon, but a space.

The description for compound commands also says

In most cases a list of commands in a compound command’s description may be separated from the rest of the command by one or more newlines, and may be followed by a newline in place of a semicolon.

but nowhere does it say that you can insert random semicolons. "Every newline can be substituted with semicolons" is simply too general a statement and not correct.

More manual evidence: in the section about lists of commands, it says (emphasis mine):

A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or a newline.

Of these list operators, && and || have equal precedence, followed by ; and &, which have equal precedence.

A sequence of one or more newlines may appear in a list to delimit commands, equivalent to a semicolon.

So a newline is equivalent to a semicolon within a list of commands.

like image 86
Benjamin W. Avatar answered Oct 04 '22 06:10

Benjamin W.