Linux – How to use while loop in csh shell command prompt

cshlinux

I am trying to use while loop in csh shell command prompt in RHEL 7.2 but am getting the below error:

$ while true
while: Expression Syntax.

The same is working in bash shell.

Best Answer

The syntax of while loops in csh is different from that of Bourne-like shells. It's:

while (arithmetic-expression)
  body
end

When csh is interactive, for some reason, that end has to appear on its own on a line.

For the arithmetic-expression to test on the success of a command, you need { cmd } (spaces are required). { cmd } in arithmetic expressions resolves to 1 if the command succeeded (exited with a 0 exit status) or 0 otherwise (if the command exited with a non-zero exit status).

So:

while ({ true })
  body
end

But that would be a bit silly especially considering that true is not a built-in command in csh. For an infinite loop, you'd rather use:

while (1)
  body
end

By contrast, in POSIX shells, the syntax is:

while cmd; do
  body
done

And if you want the condition to evaluate an arithmetic expression, you need to run a command that evaluates them like expr, or ksh's let/((...)) or the test/[ command combined with $((...)) arithmetic expansions.

Related Question