1

I want to be able to cd into a path and have it ls automatically. I have tried doing a function such as

cs() { cd "@a" ; ls}

but this results in an error saying "badly placed ()" so I do not think I can do functions. I have also tried

alias cs ' cd !:1 ; ls '

I can source my .cshrc with this but when I call it, it doesn't do anything and I am still in the same folder.

  • See also alias cwdcmd ls (assuming your csh is actually tcsh) – Stéphane Chazelas Dec 11 '18 at 22:01
1

You were very very close.  Unix loves backslashes; Unix eats backslashes for breakfast.  You need

alias cs 'cd \!:1; ls'

If you look at the documentation for csh (and its descendants), you'll see that ! refers to the history mechanism, which lets you refer to previous command(s).  The simplest example is !!, which recalls and repeats the most recent command.  !:1 means word #1 from the referenced command (where the command itself is word #0; so, for example, in grep needle *.txt!:0 is grep and !:1 is needle).

Bash and other descendants of the Bourne shell have a feature that is very similar.

C shell aliases are a little weird.  When you run an alias, the command that you typed (e.g., cs vacation_photographs) is treated as the "previous command".  So, when the alias runs, !:1 is replaced with vacation_photographs.

The catch is that this happens when the alias runs.  But history expansion happens when the alias is defined, too. So, for example, if your .cshrc says

set prompt = '% '
alias cs 'cd !:1; ls'

then !:1 is evaluated as prompt, and the alias is defined as cd prompt; ls.  To be able to refer to the command that you typed (vacation_photographs), you need to define the alias to be cd !:1; ls, and so you need to use the backslash to defer the interpretation of the !:1, so it will be evaluated when the alias is run instead of when it is defined.

If you've been doing

alias cs 'cd !:1; ls'

and it doesn't do anything (not even give you an error message), I cannot explain that.

  • Thank you! This worked. Just wondering, why is it that the \ was required? – Makuza Dec 11 '18 at 20:19
  • AFAIK, bash and zsh are the only Bourne-like shells that have implemented csh-like history expansion. – Stéphane Chazelas Dec 11 '18 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.