rubyshellrubygemscommand-line-interfacethor

Ruby thor command line tool commands


I am planning on making my first command line tool and was wondering about how the naming and commands work.

I would like my tool to function similarly to Git, in the sense that you just install it, then to run commands you just enter git clone or git commit. In many of the examples I have seen the tools are something like thor foo:bar or ./foo.rb bar.

My main question is how can I make it so if my tools name is Foo, and the command in my tool is bar, all the user has to do is run Foo bar in the command line.


Solution

  • In the case of git clone the way it works is that git program is executed and clone is passed to it as a parameter. So, if you have several scripts that should be started in a similar manner, you can create a small launcher. This code is in bash(but the script is sh compatible, so you can safely change the shebang to /bin/sh). It is very easy to write the same thing in any other language.

    #!/bin/bash
    
    command=$1
    shift
    
    case $1 in    
        cmd1)
            echo "Executing command #1"
            ./smallcmd1 "$@"
            ;;
        cmd2)
            echo "Executing command $command"
            ./smallcmd2 "$@"
            ;;
        '')
            echo 'No option specified'
            exit 1
            ;;
    
        *) echo "Invalid option"
            exit 1
            ;;
    esac
    exit $?
    

    Where smallcmds are your secondary command scripts or programs.

    Now you can execute it:

    ./mycommand smallcmd1
    

    Additional parameters can be passed as well.

    If you place this script into any $PATH directory then you can omit ./ like so:

    mycommand smallcmd1