3

For instance, I want:

/tmp: $ cs /home

to perform 'cd /home; ls' and give:

user1 user2 user3 egfile.txt
/home: $
8

You can't pass arguments to an alias, but you can to a function.

cs() {
cd "$@"
ls
}
  • 5
    Better: cd "$@" && ls, so that the function returns a nonzero status (and doesn't run ls) if cd fails. Even better: builtin cd "$@" && ls, which still works even if the function is called cd. – Gilles Sep 20 '10 at 19:33
1

Combining the answered of @garyjohn and @Gilles with an interactive? check and elaborated on the ls output formatting.

Now you can safely add this to your ~/.bashrc or /etc/bash.bashrc:

A basic version

#
# Replace every cd with cd+ls
#
if [[ $- == *i* ]]; then  # if running interactively
  cd() {
    builtin cd "$@" && ls
  }
fi

A lovely version

Filters the output of ls so that only size, mtime, and name are displayed.

if [[ $- == *i* ]]; then  # if running interactively
  cd() {
    builtin cd "$@" &&
    ls --color=always -lh | 
    awk '{ for(i=5; i<=NF; i++) {printf("%s ", $i)}; print ""} '  | 
    column -t  && echo
  }
fi
  • IMHO, "interactive?" checks are best done once in a rc file, with [ "$PS1" ] || return or [[ $- == *i* ]] || return, rather than wrapping everything in a very big if. – grawity Feb 3 '11 at 5:43
  • @grawity, I will leave the check in my answer just to be safe. Both a big if and return are valid ways. Thank you for the $- it seems to me a more reliable check. After all, one can use a shell interactively without a prompt. $PS always seemed artificial to me. – Aleksandr Levchuk Feb 3 '11 at 6:13
  • By the way, you don't need a \ after pipes or &&/|| operators. – grawity Feb 3 '11 at 13:53

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.