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?

Andrey Fedorov
  • 9,148
  • 20
  • 67
  • 99

1 Answers1

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"
}
just somebody
  • 18,602
  • 6
  • 51
  • 60
  • Could have been a shell script too? Named as a file mcd with no extension? How is a function different or better? – talkaboutquality Nov 30 '09 at 18:39
  • 5
    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. – Gordon Davisson Nov 30 '09 at 18:45
  • how is this function supposed to be called? – Tebe Jul 21 '14 at 11:56
  • ah, fine, found http://stackoverflow.com/questions/7131670/make-bash-alias-that-takes-parameter?lq=1 – Tebe Jul 21 '14 at 12:04
  • 1
    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. – just somebody Jul 21 '14 at 12:45