0

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

1
  • Please note that "custom command" is not a technical term. What you created is an executable file. It is executed by bash (since the shebang, the first line, points to the /bin/bash executable). This file is then marked as executable with the x permission. Most shell programs like that are called "scripts". Commented Jan 7, 2024 at 18:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You could check the input $1 to see whether it is -v or --version in which case you print the version and stop without executing the actual code. Idem for -h or --help.

1 Comment

yeah i got that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.