5

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.

1
  • Why would you use csh in the 21st century, especially on a Linux distribution, especially interactively? Commented Sep 15, 2017 at 13:01

3 Answers 3

8

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.

4
set i = 1
while ($i < 5)
   echo "i is $i"
   @ i++
end

or

set i = 1
while (1)
    echo "i is $i"
    @ i++
    if ($i >= 5) break
end

These output:

i is 1
i is 2
i is 3
i is 4

csh is largely superseded by the sh-shells nowadays, especially on the Linux platform (where the use of csh never really was widespread to begin with). Most BSDs also offer sh-compatible shells as their default interactive shell.

If you're learning shell programming, do consider learning the sh shell, unless your work requires you to grok csh and tcsh scripts (in this case, you may use a sh shell, like bash, as your interactive shell regardless of what types of scripts you work with).

1
  • @ i++ saved my time. I tried set i=$i+1, set i=i+1, etc. but without success. Thanks. Commented Sep 28, 2022 at 14:31
-2

Try this,

from the csh shell , man while page

set x 0
while {$x<10} {
     puts "x is $x"
     incr x
}
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .