Question

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.

Was it helpful?

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

OTHER TIPS

Making an executable with Thor is really simple. All you have to do is:

  • include the ruby shebang line.
  • require "thor" in your script.
  • define your Thor class.
  • add #{YourThorClassname}.start to the bottom of your script.

Example: my-cli.rb

#!/usr/bin/env ruby

require "thor"

class MyCLI < Thor
  desc "foo", "Prints foo"
  def foo
    puts "foo"
  end
end

MyCLI.start

Make the script executable:

chmod a+x my-cli.rb

Now you can type:

./my-cli.rb foo

You can find a similar example and more help in the Thor Wiki.

You can even rename the file to my-cli (without the .rb extension) and it still works because of the ruby shebang inside the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top