11

For my first bash script, I want to create something that's really been annoying me: when I switch folders, I want the contents of that folder to be displated automatically. I tried adding this following code to ~/.bashrc:

alias go='cd; ls'

Simple enough I thought! Not so. While typing go /etc does indeed list the contents of /etc, my working directory hasn't actually changed, I'm still in the one I was in before. How do I remedy this?

glenn jackman
  • 18,218
Ram
  • 219

2 Answers2

29

In your example, go /etc will do cd; ls /etc. That means, first, cd will change the current directory to your home directory. Then, ls /etc will display the contents of /etc.

You could achieve what you want by defining a function, like so:

function go() {
    cd "$1" && ls
}

Or just type it in the command line on a single line:

function go() { cd "$1" && ls; }

Then go /etc will do what you want.

$1 refers to the first parameter passed to the command in this example /etc. You can refer to subsequent parameters with $2, $3 and so on.

Timo Kluck
  • 9,173
-1

You may want to combine this with the built-in bash directory stack (dirs). this will give you the opportunity to type: go ..., to view the previous folder(s) in your stack, rather then type their name. an eg:

function go() { 
 if [ "$1" == "..." ]; then popd >/dev/null ; else pushd "$1" >/dev/null ; fi
 ls $@
}

you can substitute ... with other keyword, like _back. something that wont be a directory name.

you will notice the ls $@ which means all remaining parameters will be passed to ls. so if you want to go and have long listing, or reverse time listing, use: go /var -l or go /etc -ltr

CorneC
  • 1