csh alias with variable number of arguments

倾然丶 夕夏残阳落幕 提交于 2020-03-04 16:45:07

问题


I would like to create a csh alias that performs one operation if invoked without arguments and a second operation if invoked with a single argument. Does anyone know how to do this? (Attempting to refer to an argument that wasn't passed triggers an error).


回答1:


I know this is a bit late but I just ran into needing something similar and hope it might still be relevant to somebody.

You can set the arguments as an array and query based on the size of the array:

alias testing 'set args_=(\!*); if ($#args_ > 0)  echo "this command has $#args_ arguments" endif'



回答2:


Aliases in tcsh are limited; for more advanced things, I've found that the best way is to source a (t)csh script, like so:

alias my-cmd 'source ~/.tcsh/my-cmd.tcsh'

And ~/.tcsh/my-cmd.tcsh would contain something like:

if ( $1 != '' ) then
        echo "we have an argument: $1"
else
        echo "we don't have an argument"
endif

Example output:

% my-cmd
we don't have an argument
% my-cmd hello
we have an argument: hello

Now, it may also be possible to do this with just an alias, but this will be much more maintainable & cleaner in the long run, IMHO.

(I've assumed tcsh here since almost all, or perhaps even all, c shells are tcsh these days).




回答3:


Easy to do - sorry I'm late to the party.

alias iftest    'if (\\!:0 != \\!:$) echo "Last arg="\\!:$;if (\\!:0 == \\!:$) echo "No args given."'

This merely checks whether the 0th argument (=the 'iftest' itself) and the last arguments are the same, and if they are, assumes there is no argument. This is, of course, not necessarily true, but hopefully works in praxis.



来源:https://stackoverflow.com/questions/27807052/csh-alias-with-variable-number-of-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!