Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a command line tool using bash

Tags:

bash

I want to write a command line tool like git which will follow the POSIX standards. It will take the options like --help or -h , --version ..etc. But i am not getting how to do it. Can anybody tell me how to do this using bash scripting. Please help me. This is something very new to me.

Example : if the name of my tool is Check-code then i want to use the tool like ;

Check-code --help 

or

Check-code --version
like image 208
user1497818 Avatar asked Mar 14 '13 10:03

user1497818


2 Answers

So far as I know, "long options", like --help and --version are not POSIX standard, but GNU standard. For command-line utilities the POSIX standard says:

The arguments that consist of hyphens and single letters or digits, such as 'a', are known as "options" (or, historically, "flags").

To support POSIX short options options it is worth getting to know getopts (there are tutorials on the web), but it does not support GNU long options.

For long options you have to roll your own:

filename=default
while (( $# > 0 ))
do
    opt="$1"
    shift

    case $opt in
    --help)
        helpfunc
        exit 0
        ;;
    --version)
        echo "$0 version $version"
        exit 0
        ;;
    --file)  # Example with an operand
        filename="$1"
        shift
        ;;
    --*)
        echo "Invalid option: '$opt'" >&2
        exit 1
        ;;
    *)
        # end of long options
        break;
        ;;
   esac

done
like image 89
cdarke Avatar answered Sep 22 '22 13:09

cdarke


You can use the 'getopts' builtin, like so:

#!/bin/bash

# Parse arguments
usage() {
    echo "Usage: $0 [-h] [-v] [-f FILE]"
    echo "  -h  Help. Display this message and quit.
    echo "  -v  Version. Print version number and quit.
    echo "  -f  Specify configuration file FILE."
    exit
}

optspec="hvf:"
while getopts "$optspec" optchar
do
    case "${optchar}" in
        h)
            usage
            ;;
        v)
            version
            ;;
        f)
            file=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done

This only works for single character options, not for long options like -help or --help. In practice, I've never found that this is a significant restriction; any script which is complex enough to require long options is probably something that I would write in a different language.

like image 27
Barton Chittenden Avatar answered Sep 19 '22 13:09

Barton Chittenden