3

I am writing a csh alias so that I can use the following bash function in my csh :

function up( )
{
    LIMIT=$1
    P=$PWD
    for ((i=1; i <= LIMIT; i++))
    do
        P=$P/..
    done
    cd $P
    export MPWD=$P
}

(I stole the above bash function from here)

I have written this:

alias up 'set LIMIT=$1; set P=$PWD; set counter = LIMIT;  while[counter!=0] set counter = counter-1; P=$P/.. ; end cd $P; setenv MPWD=$P'

However, I am getting the following error:

while[counter!=0]: No match.
P=/net/devstorage/home/rghosh/..: Command not found.
end: Too many arguments.

and my script is not working as intended. I have been reading up on csh from here.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Chani
  • 418

2 Answers2

1

I’m not sure it’s even possible to do a while loop all on one line.  But there are several fixable errors:

  • while[counter!=0] should be while ($counter != 1) (note the spaces before and after the “!=”).
  • set counter = counter-1 should be @ counter = $counter – 1 (note the spaces before and after the ‘’).
  • P=$P/.. should be set P=$P/.. –– or better yet, set P="$P/.." (in case $P contains space(s).
  • Which reminds me, set P=$PWD should be set P="$PWD", cd $P should be cd "$P", and setenv MPWD=$P should be setenv MPWD="$P", all for the same reason.
  • And, if you do manage to get the while loop all on one line to work, you’re probably going to need a ; after the end.
  • I had to write the while loop in a single line because I was getting a horde of errors while using the the next line facility using / – Chani Jan 22 '13 at 05:26
  • OK, but my point is: have you ever gotten a ‘while loop in a single line’ *to work*?  If yes, please post an example; even if it’s something trivial like mkdir –p foo/foo/foo; while { cd foo } pwd; end. – Scott - Слава Україні Jan 22 '13 at 16:07
1

For multiple lines of code, aliases must be within single quotes, and each end of line must precede a backslash. The end of the last line must precede a single quote to delimit the end of the alias:

alias up 'set counter = \!$\
set p = "$cwd"\
while ( $counter >= 1 )\
@ counter = $counter - 1\
set p = "$p/.."\
end\
cd "$p"\
setenv mpwd "$p"'

If experiencing issues with the command editor/history, add kill -INT $$ to the end of the alias.

By the way, variables set with set are better with the equal sign separated from the variable name and content; setenv doesn't require an equal sign; math functionality is provided by @; control structures make use of parentheses; use $cwd to print the current working directory; numbers are better tested with the greater than (>; >=) and less than (<; <=) operators; \!$ denotes the last argument of the command.