11

In zsh this works fine:

alias foo=ls
foo

But this does not:

alias foo=ls; foo

Pressing enter an extra time is not an issue when running interactively. But when running through ssh it suddenly becomes a problem:

% ssh zsh@server 'alias foo=ls; foo'
zsh:1: command not found: foo

Even with a newline it does not work:

% ssh zsh@server 'alias foo=ls;
foo'
zsh:2: command not found: foo

The weird thing is that zsh knows it is aliased:

% ssh zsh@server 'alias foo=ls; alias'
foo=ls
run-help=man
which-command=whence

How do tell zsh that the aliases should be active?

2
  • It's a common problem with aliasing. I tried it using bash and csh and they behaved the same way. I hope someone could explain that.
    – Slyx
    Commented Aug 17, 2015 at 2:47
  • Bash is not a problem: ssh server 'shopt -s expand_aliases;alias jj=ls\njj'
    – Ole Tange
    Commented Aug 17, 2015 at 6:39

3 Answers 3

11

This is very well known problem which is even described in zsh manual under chapter ALIASING (see man zshmisc). The recomended way of dealing with it is to use function instead of alias:

foo() { ls; } ; foo

or even better in case of ls:

foo() { ls -- "${@:-.}"; } ; foo

ps. semicolon at the end of the function definition (list) and spaces are not needed in zsh, but as a habit from other shells I still put them.

10

You can not do it.

Because aliases were expanded only after history expansion and entire line was read in one go, so when foo was executed, the alias expansion process was gone, it's too late for the shell to recognize new alias.

The best way you can do is defining alias in .zshrc or using function like jimmij's answer or using eval:

alias foo=ls; eval foo

There's a special case with zsh -c. In this case, those aliases which were defined in .zshenv will be expanded.

3
  • That wouldn't explain why ssh host 'alias foo=bar<newline>foo' doesn't work. There's a special case for zsh -c Commented Aug 16, 2015 at 22:02
  • Or use alias foo=ls; eval foo Commented Aug 16, 2015 at 22:06
  • @StéphaneChazelas: Thanks for the information, updated with them. About ssh case, could you please make it more clear. I think the command was still read in one go.
    – cuonglm
    Commented Aug 17, 2015 at 1:53
1

Using the c-shell (tcsh to be exact) from the command line:

mymachine % alias showme "echo here it is"
mymachine % showme
here it is

or put it in the .cshrc file then source the file:

mymachine % source ~/.cshrc

mymachine % showme
here it is

mymachine % ssh garnet showme
here it is

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .