I found an answer here for a question on counting number of parameters passed argument to a BASH
script. I'm interested on the line : ${1?"Usage: $0 ARGUMENT"}
where it throws warning if no parameter is given.
Now I would like to invoke a usage function Usage
using : ${1?"Usage: $0 ARGUMENT"}
but I do not know how to do it. I tried : ${1?Usage}
and BASH
throws an error on this line. Can some suggest how to invoke a function using this.
The sample script is as below,
#!/bin/bash
function Usage() {
echo "Usage: $0 [-q] [-d]"
echo ""
echo "where:"
echo " -q: Query info"
echo " -d: delete info"
echo ""
}
# Exit if no argument is passed in
: ${1?Usage}
while getopts "qd" opt; do
case $opt in
q)
echo "Query info"
;;
d)
echo "Delete info"
;;
*)
Usage;
exit 1
;;
esac
done
What about this?
function Usage() {
echo "Usage: $0 [-q] [-d]"
echo ""
echo "where:"
echo " -q: Query info"
echo " -d: delete info"
echo ""
}
# Exit if no argument is passed in
: ${1?"$(Usage)"}
Anyhow, I think this is more readable:
if [ $# -lt 1 ] ; then
Usage
fi
Another idea would be to handle it like this:
mode=""
while getopts "qdh" opt; do
case $opt in
q)
mode="Query info"
;;
d)
mode="Delete info"
;;
h)
Usage
exit 0
;;
*)
Usage >&2
exit 1
;;
esac
done
if [ -z "${mode}" ] ; then
Usage >&2
exit 1
fi
you just need pass argument to the bash script. assume that the bash script's name is hello.sh
; for example:
#!/bin/bash
# script's name is hello.sh
: ${1?"Usage: $0 Argument"}
echo hello,$1
then chmod a+x hello.sh
then we call the script use this : bash hello.sh yourname
then echo the "hello,yourname" if you just called use bash hello.sh
and no argument for this script you will get your error message like this Usage: hello.sh Argument
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.