Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make –version custom command in linux

So, I just started to introduce myself with custom commands in Linux and created one but now I want it to be executed globally like this,
say my command is owncmd
#!/bin/bash
echo "Heya custom commands"

this works perfectly fine when I execute
$-owncmd
but I wanted to write the version or help page like :
$- owncmd –version OR owncmd –help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should make a CLI (Command Line Interface).
To do this, you should parse the command line arguments, like --help and --version. You can access them with $1, $2, …

Here is an example on your code :

#!/bin/bash

cli_help() {
    # --help: Shows help message
    echo "
owncmd - Custom command

Usage:
    owncmd [options]

Options:
    --help / -h: Show this message and exit.
    --version / -V: Show version number and exit.
"
    exit
}

cli_version() {
    # --version: Show version
    echo "owncmd v1.0"
    exit
}

# Argument
case $1 in
    "--help"|"-h")
        cli_help
        ;;
    "--version"|"-V")
        cli_version
        ;;
esac
# Main program
echo "Heya custom commands"

The program look at the first argument $1.

  • If it is --help or -h: Show an help message (function cli_help) and exit
  • If it is --version or -V: Show version number (function cli_version) and exit

ℹ️ Note: We use -V instead of -v because -v means "verbose mode", not "version".

If there is no --help or --version, the program shows Heya custom commands.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading