3

For instance, I want:

/tmp: $ cs /home

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

user1 user2 user3 egfile.txt
/home: $

2 Answers 2

8

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

cs() {
cd "$@"
ls
}
1
  • 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. Sep 20, 2010 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
3
  • 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. Feb 3, 2011 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. Feb 3, 2011 at 6:13
  • By the way, you don't need a \ after pipes or &&/|| operators. Feb 3, 2011 at 13:53

You must log in to answer this question.

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