after typing ;ls
I got this return - bash: syntax error near unexpected token `;'
how do I fix this?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityThe semicolon terminates a command. Usually you don't need it, since a newline will do. But you can use to put multiple commands on one line, e.g.
$ echo -n "hi "; echo there
hi there
or maybe more usefully:
if [ whatever ]; then
Putting a semicolon at the start of a line leaves an "empty" command before it, and apparently the shell syntax forbids it. Yash gives a useful error message:
$ yash -c '; echo hi'
yash -c:1: syntax error: a command is missing before ‘;’
And Ksh and Zsh seem to just ignore the issue:
$ zsh -c '; echo hi'
hi
(But you can't use echo foo;;
in those either, since ;;
is different from ;
, like >
is different from >>
. ;;
is used in case
statements.)
The empty command doesn't do anything anyway, so you can just leave the leading semicolon out. Or switch to Zsh, I guess.
ksh93 -c 'echo test |; cat'
complains but zsh
doesn't. In any case, I wouldn't use it anyway as |;
may become a new operator in future versions of either shell (like <>;
and >;
are already special operators in ksh93).
Apr 6, 2021 at 13:43
echo test | ; cat
with the space. Or for x in 1 2 3 4; ; do; ; echo $x; done
. In Zsh, I mean. I can see some sense in treating a semicolon a bit like a newline in that there can be many, but within a pipeline it seems a bit weird. At least it doesn't allow sprinkling &
around in the same way...
array=( ; a ; ; ; b )
. It seems ;
is equivalent to newline in most places which is kind of consistent (though I agree a bit surprising)
Apr 6, 2021 at 14:44
;
in echo one; echo two
is a control character. The ;
in if list; then ...
is part of the if
syntax. They are different, not equivalent.
if cmd & then...
(if cmd |& then
in ksh). The point is that those ;
, &
, newline, |&
... still delimit the commands there, and the then
keyword, like most keywords is only recognised as such in command position (though that's not the whole story as if (true) then echo true; fi
works in most shells (and YMMV for ((1))
or [[ x ]]
in place of (true)
))
Apr 8, 2021 at 7:17
It is the same syntax error as:
$ ;
bash: syntax error near unexpected token `;'
Which simply means that there should be a cmd
before the terminating ;
:
$ ls ;
In such cases the ;
is a metacharacter that is defined as:
metacharacter
A character that, when unquoted, separates words.
Not equivalent to the ;
in the compound command:
if list; then list; else list; fi
As, in this case, it is part of the syntax of the command.
;ls
? If so, why? The easy answer is along the lines of "don't do that", but has deeper explanations, depending on your curiosity.:;ls
instead... Or use Ksh or Zsh, which just ignore the empty command. It's somewhat interesting actually that it isn't allowed.