Results 1 to 5 of 5

Thread: BASH script/alias to LS after CD

  1. #1
    Join Date
    Sep 2008
    Location
    39°43.'N/104°46.6'W
    Beans
    19
    Distro
    Ubuntu 8.10 Intrepid Ibex

    BASH script/alias to LS after CD

    How do I program my BASH shell to automatically 'ls' after I've 'cd'?

    Code:
    cd $*;ls
    doesn't work. I want to simply type:
    Code:
    cd dir
    and have it automatically list contents after changing directory.

    Any help?

  2. #2
    Join Date
    Jul 2009
    Location
    London
    Beans
    1,480
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: BASH script/alias to LS after CD

    put this function in your .bashrc:
    Code:
    function cd()
    {
     builtin cd "$*" && ls
    }

  3. #3
    Join Date
    Sep 2008
    Location
    canada
    Beans
    Hidden!

    Re: BASH script/alias to LS after CD

    [edit]Oops noticed that DaithiF has already answered.

    Only the last command in the alias gets the passed argument.
    Code:
    alias cd="echo changing to $1;cd $1;echo changing $1"
    
    steve@steve-HP-Compaq-dc7100-CMT-PJ075UA:~$ cd Downloads/
    changing to
    changing Downloads/
    
    steve@steve-HP-Compaq-dc7100-CMT-PJ075UA:~$ pwd
    /home/steve
    Last edited by pl@yer; March 17th, 2011 at 01:57 PM.

  4. #4
    Join Date
    Jul 2009
    Location
    London
    Beans
    1,480
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: BASH script/alias to LS after CD

    Quote Originally Posted by pl@yer View Post
    Only the last command in the alias gets the passed argument.
    Hi, thats not strictly true. when bash encounters an alias it just expands that alias, it doesn't pass it any arguments.

    so in your example:
    Code:
    alias cd="echo changing to $1;cd $1;echo changing $1"
    cd Downloads/
    your cd Downloads command gets expanded to:
    Code:
    echo changing to $1;cd $1; echo changing $1 Downloads/
    $1 is empty, so it ends up as:
    Code:
    echo changing to ;cd; echo changing Downloads/
    which i guess is why it looked to you like the last command was getting passed the argument.

  5. #5
    Join Date
    Sep 2008
    Location
    canada
    Beans
    Hidden!

    Re: BASH script/alias to LS after CD

    Hey,
    Thanks for the explanation.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •