A Scripter's Notes

Emacs, scripting and anything text oriented.

Writing aliases with optional arguments in tcsh

Some times I would need to define an alias in tcsh which can have optional arguments. tcsh doesn’t seem to support that directly.

Here’s how I solve that problem.

If you have an alias alias test 'echo \!:1*' and if you run test abc def, you will get the output abc def.

!:1* prints out all the arguments starting from argument 1 till the last where even argument 1 is optional. If that argument doesn’t exist, the variable will be assigned a null value.

But tcsh will not complain about it – the * after !:1 is the beauty. On the other hand, if I have an alias alias test2 'echo \!:1', and if I run test – with zero arguments – tcsh will give an error.

So extending that, I have the below alias defined to grab an argument of any index.

alias opt_args 'set arg1 = `echo \!:1* | awk '"'"'{ print $1 }'"'"'`; \\
                echo -n "Arg num 1 = $arg1 "; \\
                set arg2 = `echo \!:2* | awk '"'"'{ print $1 }'"'"'`; \\
                echo -n "Arg num 2 = $arg2 "; \\
                set arg3 = `echo \!:3* | awk '"'"'{ print $1 }'"'"'`; \\
                echo -n "Arg num 3 = $arg3 "; \\
                echo ""; \\
               '

You can test this alias by running these commands:

opt_args abc
opt_args abc def
opt_args abc def ghi
opt_args abc def ghi jkl

Comments

comments powered by Disqus