Reputation: 3
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
Upvotes: 0
Views: 797
Reputation: 193
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
.
--help
or -h
: Show an help message (function cli_help
) and exit--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
.
Upvotes: 1
Reputation:
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.
Upvotes: 1