21

Trying to create:

alias mcd="mkdir $1; cd $1"

Getting:

$ mcd foo
usage: mkdir [-pv] [-m mode] directory ...
-bash: foo: command not found

What am I doing wrong?

1
  • 1
    This one was asked and answered first! Commented Apr 24, 2015 at 14:46

1 Answer 1

32

An alias can only substitute the first word of a command with some arbitrary text. It can not use parameters.

You can instead use a shell function:

mcd()
{
  test -e "$1" || mkdir "$1"
  cd "$1"
}
Sign up to request clarification or add additional context in comments.

5 Comments

Could have been a shell script too? Named as a file mcd with no extension? How is a function different or better?
It wouldn't work as a shell script, because the script would run in a subshell. In order for the cd to have the intended effect, it has to run in the caller's shell, not a subshell.
how is this function supposed to be called?
this function is supposed to be called just like any other command, be it implemented by a function, a builtin or external command. you just need to make sure the function is defined in your shell, which can be done by putting it in your shell startup files.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.