I want to make a bash script that works like a makefile.
It would have the options like -archive, -clean, -backup and etc.
The only requirement is that it must have the -o argument so it specifies a name.
The problem I have right now is that I don’t know how to pull out the .c files from the arguments.
For example, if I inputed
./compile.sh -o name -backup hello_world.c print.c
How would I compile this?
Here’s the code I have so far.
#!/usr/local/bin/bash
if [ $1 != '-o' ]; then
echo "ERROR -o wasn't present as first argument"
echo "HELP"
echo "BASH syntax: $ compile –o filename –clean –backup –archive -help cfilenames"
echo "WHERE:"
echo "$ Unix Prompt"
echo "comiple Name of bash program"
echo "-o filename Mandatory Argument"
echo "-clean Optional and when present deletes all .o files"
echo "-backup Optional and copies all .c and .h files into backup directory"
echo "-archive Optional and Tars content of source directory. Then moved to backup directory"
echo "-help Provides list of commands"
echo "cfilenames Name of files to be compiled together"
fi
NAME=$2
shift
shift
options=$@
arguments=($options)
index=0
for argument in $options
do
index=`expr $index + 1`
case $argument in
-clean) echo "clean" ;;
-backup) echo "backup"
mv -f *.c ~/backup
mv -f *.c ~/backup ;;
-archive) echo "archive"
tar -zcvf backup.tar.gz *
mv -f backup.tar.gz ~/backup/backup.tar.gz
;;
-help) echo "help"
echo "HELP"
echo "BASH syntax: $ compile –o filename –clean –backup –archive -help cfilenames"
echo "WHERE:"
echo "$ Unix Prompt"
echo "comiple Name of bash program"
echo "-o filename Mandatory Argument"
echo "-clean Optional and when present deletes all .o files"
echo "-backup Optional and copies all .c and .h files into backup directory"
echo "-archive Optional and Tars content of source directory. Then moved to backup directory"
echo "-help Provides list of commands"
echo "cfilenames Name of files to be compiled together"
;;
esac
done
exit;
Thanks
You appear to be looking for getopts(1P), a bash built-in for parsing options. You use it as follows:
Read more: http://aplawrence.com/Unix/getopts.html#ixzz1qAQ29TFW
If you’d like to use long options, you can use getopt(1), a separate program that you can invoke from bash. It is part of
linux-util, which is part of the default install for most distros, or at least part of the base packages.