I'm trying to write bash script that can be launched with operational arguments and based on that either append, delete or overwrite data file, but when I use -a or -o arguments, the file stays empty or only white characters. What is the problem? Thanks!
#!/bin/bash
FILE=/home/xxx/file.data
while getopts 'hadov' CHOICE; do
case "$CHOICE" in
h) echo "-h (help)">&2
echo "-a (append)">&2
echo "-d (delete)">&2
echo "-o (overwrite)">&2
echo "-v (view)">&2;;
a) echo $OPTARG >> $FILE;;
d) if [ -f $FILE ]; then rm $FILE; else echo "file does not exist" > /dev/null;fi;;
v) if [ -f $FILE ]; then cat $FILE; else echo "file does not exist" > /dev/null;fi;;
o) echo $OPTARG > $FILE;;
?) echo bad opt – ${CHOICE} > /dev/stderr
echo bad choice, use -h for help >&2
exit 1;;
esac
done
if [ $OPTIND -eq 1 ];
then
echo "no choice, use -h for help" >/dev/stderr;
exit 1;
fi;
CodePudding user response:
Your getopts
command has the wrong syntax.
You must seperate the optional arguments with a ?
, if you don't expect a argument value, and :
if you expect a argument value.
So your code with while
-line replaced with this
while getopts 'h?a:d?o:v' CHOICE; do
and ./<Script> -o test
will produce a file with test
in it.
For more information, i would suggest you to read the man page