I want to create a bash script that accepts some arguments and has the following usage:
<code>$ ./execute.sh add person --id 123 --name John
</code>
<code>$ ./execute.sh add person --id 123 --name John
</code>
$ ./execute.sh add person --id 123 --name John
I found getopts
and was trying to use it to parse the options but without success. My current code is:
<code>#!/bin/bash
command=$1
entity=$2
while getopts ":id:name:" opt; do
echo "opt: ${opt}"
case ${opt} in
id)
id=$OPTARG
;;
name)
name=$OPTARG
;;
?)
echo "Invalid option: $OPTARG" 1>&2
;;
:)
echo "Option -$OPTARG requires an argument." 1>&2
;;
esac
done
if [ -z "${id}" ] || [ -z "${name}" ]; then
echo "Missing required options" 1>&2
echo "Usage: $0 <command> <entity> --id <number> --name <string>"
exit 1
fi
case $command in
add)
echo "adding entity $entity..."
;;
*)
echo "invalid command: $command"
exit 1
;;
esac
</code>
<code>#!/bin/bash
command=$1
entity=$2
while getopts ":id:name:" opt; do
echo "opt: ${opt}"
case ${opt} in
id)
id=$OPTARG
;;
name)
name=$OPTARG
;;
?)
echo "Invalid option: $OPTARG" 1>&2
;;
:)
echo "Option -$OPTARG requires an argument." 1>&2
;;
esac
done
if [ -z "${id}" ] || [ -z "${name}" ]; then
echo "Missing required options" 1>&2
echo "Usage: $0 <command> <entity> --id <number> --name <string>"
exit 1
fi
case $command in
add)
echo "adding entity $entity..."
;;
*)
echo "invalid command: $command"
exit 1
;;
esac
</code>
#!/bin/bash
command=$1
entity=$2
while getopts ":id:name:" opt; do
echo "opt: ${opt}"
case ${opt} in
id)
id=$OPTARG
;;
name)
name=$OPTARG
;;
?)
echo "Invalid option: $OPTARG" 1>&2
;;
:)
echo "Option -$OPTARG requires an argument." 1>&2
;;
esac
done
if [ -z "${id}" ] || [ -z "${name}" ]; then
echo "Missing required options" 1>&2
echo "Usage: $0 <command> <entity> --id <number> --name <string>"
exit 1
fi
case $command in
add)
echo "adding entity $entity..."
;;
*)
echo "invalid command: $command"
exit 1
;;
esac
But with that, the output I have is:
<code>Missing required options
Usage: ./execute.sh <command> <entity> --id <number> --name <string>
</code>
<code>Missing required options
Usage: ./execute.sh <command> <entity> --id <number> --name <string>
</code>
Missing required options
Usage: ./execute.sh <command> <entity> --id <number> --name <string>
So, it seems that it’s not parsing the options at all, but I’m not sure why.
Any help and tips appreciated.