PDA

View Full Version : Using Options with Custom Commands in Terminal




gtr053
Sep 7, 2010, 11:39 AM
I often find myself making a directory and then immediately moving to it. I created a shortcut by modifying my .bash_profile file. I added the following code to the bottom:
mac(){
mkdir "$1"
cd "$1"
}
That way, all I have to type into Terminal in order to make and change to a new directory is this
mac [directory]
I'd like to be able to use -p, -v, -m, etc. for mkdir and -p, -l, -n, -v, etc. for cd. How would you suggest going about and doing that, seeing as I am combining two commands into one?
I was thinking something along the lines of this:
mac(){
mkdir "$1 $2"
cd "$1 $3"
}
Let me know what you think.



balamw
Sep 8, 2010, 08:06 AM
I'd like to be able to use -p, -v, -m, etc. for mkdir and -p, -l, -n, -v, etc. for cd. How would you suggest going about and doing that, seeing as I am combining two commands into one?

Just curious. Which cd supports all those options, and what do they do? AFAIK, bash's cd only supports -L (default) and -P (don't follow links).

http://ss64.com/bash/cd.html

B

ianray
Sep 8, 2010, 10:55 AM
Snow leopard bash cd supports only -L, -P options -- both of which seem somewhat irrelevant for your scenario.

Snow leopard mkdir -v can also be considered uninteresting; that leaves -p which could be always set, and -m which takes an argument.

When using numbered arguments, then care is needed with quotes: mac(){
mkdir -p $2 "$1"
cd "$1"
}

Usage: mac foo "-m 0777"

Alternatively, and more flexibly: mac(){
arg="$1"
shift
mkdir $* "$arg"
cd "$arg"
}


Usage: mac foo -m 0777

Enjoy :)

gtr053
Sep 8, 2010, 12:45 PM
I am somewhat new with Terminal. I may not even need any other options than -p for mkdir but I just wanted to enable them in case I ever need them.

chown33
Sep 8, 2010, 01:30 PM
I am somewhat new with Terminal. I may not even need any other options than -p for mkdir but I just wanted to enabled them in case I ever need them.

You could always use -p. You could define it as the function macp().

When making commands that are easy to type, adding options usually works against the goal of being easy to type. It's simpler to make a family of commands with slight spelling variations, each of which does exactly one thing (example: 'll' as a shortcut for 'ls -l'). This also has the advantage of not having to write, test, and debug complicated options-parsing schemes.
http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/getopt.1.html

For example, define a mac() function and a macp() function. Or define mac() to use the -p option, and define some other function name to do a new task, once you've identified what that task is.
http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it

gtr053
Sep 8, 2010, 11:39 PM
I guess I could do that. I think I will just always use -p with mkdir in the mac command.

And I like that Wikipedia article you posted. :)