Search code examples
cshtcsh

csh while loop in single line


I was trying to get the date printed for the ping command is going, to simulate similar effect as in bash ping 1.1.1.1 -O | while read pong; do echo "$(date): $pong"; done, but could not make it work so far.

Tried the following on a csh shell, but does not work: ping 1.1.1.1 -O | while ( 1 ) echo `date` end

What I am missing ? appreciate your help.


Solution

  • What you're missing is that the syntax used by csh and tcsh is not nearly as general and flexible as the syntax used by bash and other Bourne-derived shells.

    csh does have a special-case syntax for 1-line if statements:

    if (condition) statement
    

    but it doesn't have anything similar for loops:

    % while (1) echo hello
    while: Expression Syntax.
    

    and it doesn't allow piping a command's output into a loop.

    If you must use csh/tcsh for some reason, you can write a script to encapsulate your while loop and pipe your command's output to that script, or you can invoke an sh or bash process to do the work for you:

    csh% bash -c 'ping 1.1.1.1 -O | while read pong; do echo "$(date): $pong"; done'
    

    (I use csh and tcsh, both interactively and for scripting, for a number of years. My own solution was first to start using bash for scripting, and then to give up on tcsh entirely and use bash as my default shell. It's a bit of a learn curve, and there are some tcsh features that aren't quite as convenient in bash, but I recommend it.)

    I am legally required to post this link:

    https://web.mit.edu/ghudson/info/csh.whynot