Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

bash script not writing into a file

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;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading