I have seen many examples for how to use getopts. But I know very basic of bash and I was not able to to implement it in my situation. I really appreciated if anyone expert can show me the template.
I have a script with minimum 6 and maximum 10 input. Here is a brief description:
script.sh -P passDir -S shadowDir -G groupDir -p password -s shadow
User must provide argument for -P -S -G and if not I must display usage and close the program. If argument are provided I need them to be saved into an appropriate variable.
But -p and -s is optional. However, if there is no -p I should do some tasks and if there is no -s I should do some other tasks and if none of them is there I should do some other tasks.
Following is what I have written so far but it stock in the for loop.
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "Only root may add a user to system"
exit 2
else
usage() { echo "Usage: $0 [-P <password file path>] [-S <shadow file path>] [-G <group path>]" 1>&2; exit 1; }
passDir=""
shadowDir=""
groupDir=""
while getopts ":P:S:G:" inp; do
case "${inp}" in
P)
$passDir = ${OPTARG};;
S)
$shadowDir = ${OPTARG};;
G)
$groupDir = ${OPTARG};;
*)
usage;;
esac
done
echo "${passDir}"
echo "${shadowDir}"
echo "g = ${groupDir}"
fi
At the moment is user does not enter arguments nothing will be shown and if there is arguments it goes inside a loop!