1

So here I've created, or at least tried to create an alias for a command that accepts a command-line argument, makes a new directory with that name, and goes to it.

alias newfolder='mkdir $2 ; cd "$(history | tail -2 | awk '\''NR == 1'\'' | awk '\''{print $3}'\'')"'

The alias created successfully, but when I want to run the command with a command-line argument, I get this error message.

username:~/workspace (master) $ newfolder a
mkdir: missing operand
Try 'mkdir --help' for more information.
bash: cd: newfolder='mkdir: No such file or directory
0

1 Answer 1

2

You need a function, not an alias. Try:

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

Example:

$ pwd
/tmp
$ newfolder dir1/dir2
$ pwd
/tmp/dir1/dir2

Notes:

  1. The -p option to mkdir tells it to create missing parent directories if needed. In the above example, dir1 did not exist but mkdir -p dir1/dir2 created both dir1 and dir2.

  2. Because we use the shell operator &&, the cd command will only be performed if the mkdir command succeeded.

  3. Aliases are useful in very simple cases where a fixed string can be substituted for a word. Aliases do not process arguments.

  4. Because we are using a shell function in place of an alias, we can reference the arguments, such as, in this case, $1, according to our needs.

Not the answer you're looking for? Browse other questions tagged .