Using Options with Custom Commands in Terminal

Discussion in 'Mac Programming' started by gtr053, Sep 7, 2010.

  1. macrumors member

    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:
        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:
        mkdir "$1 $2"
        cd "$1 $3"
    Let me know what you think.
  2. Moderator


    Staff Member

    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).

  3. macrumors 6502

    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:
        mkdir -p $2 "$1"
        cd "$1"
    mac foo "-m 0777"
    Alternatively, and more flexibly:
        mkdir $* "$arg"
        cd "$arg"
    mac foo -m 0777
    Enjoy :)
  4. macrumors member

    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.
  5. macrumors 603

    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.

    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.'t_gonna_need_it
  6. macrumors member

    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. :)

Share This Page