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
>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
--helpor-h: Show an help message (functioncli_help) and exit - If it is
--versionor-V: Show version number (functioncli_version) and exit
ℹ️ Note: We use
-Vinstead of-vbecause-vmeans "verbose mode", not "version".
If there is no --help or --version, the program shows Heya custom commands.