Chani
Chani

Reputation: 5165

Error converting a bash function to a csh alias

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.

I am not an expert in csh and what I have written above is my first csh script. Please let me know what I am doing wrong.

Upvotes: 0

Views: 1604

Answers (3)

Matheus Garcia
Matheus Garcia

Reputation: 41

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 = $1\
set p = $cwd\
while $counter != 0\
@ counter = $counter - 1\
set p = $p/..\
end\
cd $p\
setenv mpwd $p'

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 (though aren't required for simple tests); use $cwd to print the current working directory.

Upvotes: 0

Navaneeth Krishnan M
Navaneeth Krishnan M

Reputation: 141

You can also do this

alias up 'cd `yes ".." | head -n\!* | tr "\n" "\/"`'

yes ".." will repeat the string .. indefinitely; head will truncate it to the number passed as argument while calling the alias ( !* expands to the arguments passed; similar to $@ ) and tr will convert the newlines to /.

radical7's answer seems to be more neat; but will only work for tcsh ( exactly wat you wanted ). This should work irrespective of the shell

Upvotes: 2

radical7
radical7

Reputation: 9114

You can use the csh's repeat function

alias up 'cd `pwd``repeat \!^ echo -n /..`'

No loops needed (which is handy, because while constructs in tcsh seem very finicky)

Upvotes: 1

Related Questions