make and change into a directoryy

Chris F.A. Johnson cfaj-uVmiyxGBW52XDw4h08c5KA at public.gmane.org
Sat May 20 15:28:01 UTC 2006


On Fri, 19 May 2006, Sy Ali wrote:

> I'm trying to create a simple script to md + cd into a directory.
> It's much more difficult than I expect.
>
> First, I learn that I can't do something trivial like this.
>
> $ cat > ~/script.sh
> md $1
> cd $1
> ^D
> $ chmod +x script.sh
> ~/script.sh
>
> but this I already knew.  I tried working with an alias, but I can't
> figure out how to use $1 twice or how to spit out two commands with
> one alias.
> 
> i.e. this stuff won't work:
> alias mcd='md $1 ; cd $1'
> alias mcd='md {$1} ; cd {$1}'
>
> but even if I do this:
> alias mcd='echo $1 ; echo $1'
>
> then $1 is only usable once.
> $ mcd testing
> => 
> => testing

    An alias doesn't do any replacement of arguments.

> Then I tried to step back and have my md+cd in a script.
>
> I make a script which spits out the commands, like this:
> $ cat > ~/mcd.sh
> echo md $1
> echo cd $1
> ^D
> $ chmod +x script.sh
>
> and then I make an alias like this:
> $ alias mcd='eval $(~/mcd.sh)'
> 
> and I run it like:
> $ mcd testing
>
> but this will only evaluate the first expression in ~/script.sh which
> makes the testing directory (but does not cd into it)

    I doubt that it does even that. You are not passing any arguments
    to the script.

> I guess my question is:
> How can I make an alias do two things?

    You don't. An alias is a simple replacement of the command. As the
    bash man page says, "For almost every purpose, aliases are
    superseded by shell functions."

    You cannot use a script, because a process cannot affect its
    parent.

    Write a function, and put it in your .bash_profile or .bashrc:

mcd()
{
    mkdir -p "$1" && cd "$1"
}

    To make it work in your current shell, enter it at the prompt.

-- 
    Chris F.A. Johnson                      <http://cfaj.freeshell.org>
    ===================================================================
    Author:
    Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list