csh alias with variable number of arguments

后端 未结 3 426
孤街浪徒
孤街浪徒 2021-01-28 13:58

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

相关标签:
3条回答
  • 2021-01-28 14:42

    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'
    
    0 讨论(0)
  • 2021-01-28 14:50

    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.

    0 讨论(0)
  • 2021-01-28 14:58

    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).

    0 讨论(0)
提交回复
热议问题