Bash while() loop :: Does this process cmd line arguments? - bash

I'm a Bash newbie, and I'm puzzling through a Bash script where I see this:
while [ $# -ge 2 ]
if [ "x$1" = "x-a" ]; then
echo "STR_A = $2" >>tmpFile.txt
...do more stuff...
elif [ "x$1" = "x-b" ]; then
echo "STR_B = $2" >>tmpFile.txt
...do more stuff...
else
usage
done
The script takes in four (or five?) command line arguments, and that usage function is:
usage() {
echo "usage: myscript -a STR_A | -b STR_B" 1>&2
exit 1
}
So suppose I ran the script like this:
me#ubuntu1:~$./myscript -A apple -B banana
I'm guessing that this code processes the script's command line arguments. I think that the outer while() loop steps through the command line arguments after argument 1, which would be myscript. The inner if() statements check to see an -a or -b flag is used to supply arguments, and then records the text string that follows in tmpFile.txt. Anything outside of those parameters is rejected and the script exits.
A lot of these assumptions rest on the bet that the outer while() loop...
while [ $# -ge 2 ]
...means "parse the BASH argv[] after the first argument", (to put this in C terms.) If that's not a correct assumption, then I have no idea what's going on here. Any feedback is appreciated, thank you!

Some code explanation.
while [ $# -ge 2 ]
There is a missing do for the loop.
This should loop forever if there are two or more arguments, unless shift is used. If there are less than two arguments, the loop does not even start.
if [ "x$1" = "x-a" ]; then
In distant past, it was common to prevent empty strings by adding an extra letter. Nowadays you would if [ "$1" = "-a" ]; then.
else
usage
Note that the usage is called from within the loop. So, if I would call the script as myscript -a, I would not get a usage message. On the other hand, if I would myscript bla bla, I would get an endless stream of error messages, which is probably not what you want.
I would seriously edit the script; determine whether the while is indeed a loop-forever or whether it is used instead of an if, and try the getops for argument parsing.

This doesn't help understand the code you're reading, but I do option parsing like this:
# inititialize vars, not strictly required in this case
a=''
b=''
# process options
while getopts "ha:b:" opt; do
case $opt in
a) a=$OPTARG ;;
b) b=$OPTARG ;;
*) usage ;;
esac
done
# shift after the processing
shift $((OPTIND - 1))
# look for error conditions
if [[ -n $a && -n $b ]]; then
echo "only one of -a or -b should be given" >&2
exit 1
fi
getopts is a bash builtin

Related

Simple bash shell script to ensure that provides two arguments

I'm trying to write simple greetings script in bash to ensure that the user provides at least two arguments. 1)The first argument provides how long we want to delay before the greeting prints. 2) The second argument provides what message we want to display. Sorry I'm fairly new to shell scripting.
#!/bin/sh
if[$# -ge 2]
then
sleep $1
shift
banner $*
else
echo "Usage: Greeing seconds word(s)"
fi
You should use:
#!/bin/sh
if [ $# -ge 2 ]
then
sleep $1
shift
banner $*
else
echo "Usage: Greeing seconds word(s)"
fi
You were missing:
a space after if
a space around [ and ]
If you want to ensure that 2 arguments are given, use ${2?}. For example:
echo First arg is ${1?Missing first argument}. 2nd arg is ${2?Missing 2nd argument}

getopts in bash, script was working before and now I'm baffled

So I have a couple of getopts in my bash script. Here's an example of a working one.
FOUND=
SEARCH=
COUNT=0
while getopts "ips:flenkc" OPTION
do
case $OPTION in
i)
FOUND=1
let "COUNT++"
;;
p)
FOUND=2
let "COUNT++"
;;
s)
FOUND=3
SEARCH=$OPTARG
let "COUNT++"
;;
esac
done
Later on a case statement that checks to see if count=1 (meaning, only one of the following, i, p, and s, are used in the call) Not important except that it determines the main action being done.
Now the getopts thing in question. This was working before, and now it's not. The goal is to make it so that if someone wants to input data, they can do so with the following bash command.
./programname -i -f Mary -l Sue -e smary#email.com -n 555-555-5555
Where, when -i is used, we must have -f, -l, -e, and -n (for first name, last name, e-mail, and number).
The code I was using: Warning, code is full of syntax errors. If you're learning bash, I highly recommend you do not use anything you see here in my post.
if [ $FOUND == "1" ]
then
echo "You have chosen to insert things."
FIRST=
LAST=
EMAIL=
NUMBER=
while getopts "if:l:e:n:" OPTION
do
case $OPTION in
f)
FIRST=$OPTARG
;;
l)
LAST=$OPTARG
;;
e)
EMAIL=$OPTARG
;;
n)
NUMBER=$OPTARG
;;
esac
done
if [[ -z $FIRST ]] || [[ -z $LAST ]] || [[ -z $EMAIL ]] || [[ -z $NUMBER ]]
echo "Error!!! Some input is missing!!!"
usage // display usage
exit 1
fi
echo -e $FIRST"\t"$LAST"\t"$EMAIL"\t"$NUMBER >> contacts
fi
Before this program would work, but now, not even a single thing is making it to input for FIRST, LAST, EMAIL, and NUMBER (in my attempts to change the code to see if it was making it to certain steps).
What am I doing wrong with the getopts? It was working fine before, but now.... it's not working at all!
One thing worth noting up front: if your script has already called getopts once, another getopts call will start AFTER all options and therefore effectively do nothing; reset OPTIND to 1 before each subsequent getopts calls to have them reprocess all options.
Your code has both syntax errors and is worth cleaning up in general:
The if [[ -z ... statement was missing a then.
The // after usage would have caused a syntax error - POSIX-like shells use # as the comment char.
Since this is bash script, stick with using [[ ... ]] consistently (no need for [ ... ]) and/or use (( ... )) for arithmetic operations.
Specifically, avoid [ ... == ... ], because it mixes POSIX syntax - [ ... ] - with Bash-specific syntax - == ( POSIX only supports =).
If you do use [ ... ], be sure to double-quote variable references, to be safe.
No need for multiple [[ ... ]] expressions to OR them together - do it in a single [[ ... || ... || ... ]].
It's best to avoid all-uppercase shell-variable names so as to avoid conflicts with environment variables and special shell variables.
Output error messages to stderr, using >&2.
Enclose the entire argument to echo -e in double-quotes to protect variable values from possibly unwanted expansions.
Mere syntax errors can usually be caught using shellcheck.net.
Putting it all together, we get:
#!/usr/bin/env bash
# ... code that sets $found
# If you've already processed args. with getopts above,
# you must reset OPTIND to process them again.
OPTIND=1
if (( found == 1 )) # found is numeric, use arithmetic expression to compare
then
echo "You have chosen to insert things."
first= last= email= number= # don't use all-uppercase var. names
while getopts "if:l:e:n:" option
do
case $option in
f)
first=$OPTARG
;;
l)
last=$OPTARG
;;
e)
email=$OPTARG
;;
n)
number=$OPTARG
;;
esac
done
if [[ -z $first || -z $last || -z $email || -z $number ]]; then
echo "Error!!! Some input is missing!!!" >&2
usage # display usage
exit 1
fi
echo -e "$first\t$last\t$email\t$number" >> contacts
fi

How to create a flag with getopts to run a command

I need help with my getopts, i want to be able to run this command ( mount command) only if i pass a flag ( -d in this case).
below output is what i have on my script but it doesn't seem to work.
CHECKMOUNT=" "
while getopts ":d" opt
do
case "$opt" in
d) CHECKMOUNT="true" ;;
usage >&2
exit 1;;
esac
done
shift `expr $OPTIND-1`
FS_TO_CHECK="/dev"
if [ "$CHECKMOUNT" = "true" ]
then
if cat /proc/mounts | grep $FS_TO_CHECK > /dev/null; then
# Filesystem is mounted
else
# Filesystem is not mounted
fi
fi
Your script has a number of problems.
Here is the minimal list of fixes to get it working:
While is not a bash control statement, it's while. Case is important.
Whitespace is important: if ["$CHECKMOUNT"= "true"] doesn't work and should cause error messages. You need spaces around the brackets and around the =, like so: if [ "$CHECKMOUNT" = "true" ].
Your usage of getopts is incorrect, I'm guessing that you mistyped this copying an example: While getopts :d: opt should be: while getopts ":d" opt.
Your usage of shift is incorrect. This should cause error messages. Change this to: shift $((OPTIND-1)) if you need to shift OPTIND.
The bare text unknocn flag seems like a comment, precede it with #, otherwise you'll get an error when using an unknown option.
There is no usage function. Define one, or change usage in your \?) case to an echo with usage instructions.
Finally, if your script only requires a single optional argument, you might also simply process it yourself instead of using getopt - the first argument to your script is stored in the special variable $1:
if [ "$1" = "-d" ]; then
CHECKMOUNT="true"
elif [ "$1" != "" ]; then
usage >&2
exit 1
fi

How to create a bash script that takes arguments?

I already know about getopts, and this is fine, but it is annoying that you have to have a flag even for mandatory arguments.
Ideally, I'd like to be able to have a script which receives arguments in this form:
script.sh [optional arguments] [anything required]
for example
script.sh -rvx output_file.txt
where the script says you HAVE to have an output file. Is there any easy way to do this?
As far as I know, with getopts it would have to look like: script.sh -rvx -f output_file.txt, and that is just not very clean.
I can also use python if necessary, but only have 2.4 available, which is a bit dated.
Don't use the getopts builtin, use getopt(1) instead. They are (subtly) different and do different things well. For you scenario you could do this:
#!/bin/bash
eval set -- $(getopt -n $0 -o "-rvxl:" -- "$#")
declare r v x l
declare -a files
while [ $# -gt 0 ] ; do
case "$1" in
-r) r=1 ; shift ;;
-v) v=1 ; shift ;;
-x) x=1 ; shift ;;
-l) shift ; l="$1" ; shift ;;
--) shift ;;
-*) echo "bad option '$1'" ; exit 1 ;;
*) files=("${files[#]}" "$1") ; shift ;;
esac
done
if [ ${#files} -eq 0 ] ; then
echo output file required
exit 1
fi
[ ! -z "$r" ] && echo "r on"
[ ! -z "$v" ] && echo "v on"
[ ! -z "$x" ] && echo "x on"
[ ! -z "$l" ] && echo "l == $l"
echo "output file(s): ${files[#]}"
EDIT: for completeness I have provided an example of handling an option requiring an argument.
If you are using getops, just shift by $OPTIND-1 after your case statement. Then what is left in $* will be everything else, which is probably what you want.
shift $(( ${OPTIND} - 1 )); echo "${*}"
You're are suffering from illusions; using getopts does not require mandatory arguments prefixed by a flag letter. I tried to find a suitable example from my corpus of scripts; this is a semi-decent approximation. It is called rcsunco and is used to cancel a checkout from RCS. I haven't modified it in a while, I see; I use it quite often (because I haven't migrated from RCS completely, yet).
#!/bin/sh
#
# "#(#)$Id: rcsunco.sh,v 2.1 2002/08/03 07:41:00 jleffler Exp $"
#
# Cancel RCS checkout
# -V print version number
# -n do not remove or rename checked out file (like SCCS unget) (default)
# -r remove checked out file (default)
# -k keep checked out file as $file.keep
# -g checkout (unlocked) file after clean-up
# -q quiet checkout
: ${RCS:=rcs}
: ${CO:=co}
remove=yes
keep=no
get=no
quiet=
while getopts gknqrV opt
do
case $opt in
V) echo "`basename $0 .sh`: RCSUNCO Version $Revision: 2.1 $ ($Date: 2002/08/03 07:41:00 $)" |
rcsmunger
exit 0;;
g) get=yes;;
k) keep=yes;;
n) remove=no;;
q) quiet=-q;;
r) remove=yes;;
*) echo "Usage: `basename $0 .sh` [-{n|g}][-{r|k}] file [...]" 1>&2
exit 1;;
esac
done
shift $(($OPTIND-1))
for file in $*
do
rfile=$(rfile $file)
xfile=$(xfile $rfile)
if $RCS -u $rfile
then
if [ $keep = yes ]
then
if [ -f $xfile ]
then
mv $xfile $xfile.keep
echo "$xfile saved in $xfile.keep"
fi
elif [ $remove = yes ]
then rm -f $xfile
fi
if [ $get = yes ] && [ $remove = yes -o $keep = yes ]
then $CO $quiet $rfile
fi
fi
done
It's only a semi-decent approximation; the script quietly does nothing if you don't supply any file names after the optional arguments. However, if you need to, you can check that the mandatory arguments are present after the 'shift'. Another script of mine does have mandatory arguments. It contains:
...
shift $(($OPTIND - 1))
case $# in
2) case $1 in
install) MODE=Installation;;
uninstall) MODE=Uninstallation;;
*) usage;;
esac;;
*) usage;;
esac
So, that command (jlss) can take optional arguments such as -d $HOME, but requires either install or uninstall followed by the name of something to install. The basic mode of use is:
jlss install program
But the optional mode is:
jlss -d $HOME -u me -g mine -x -p install program
I didn't show all of jlss because it has about 12 options - it isn't as compact as rcsunco.
If you were dealing with mandatory arguments before option arguments, then you'd have to do a bit more work:
You'd pick up the mandatory arguments, shifting them out of the way.
Then you process the optional arguments with the flags.
Finally, if appropriate, you handle the extra 'file name' arguments.
If you are dealing with mandatory arguments interspersed with option arguments (both before and after the mandatory ones), then you have still more work to do. This is used by many VCS systems; CVS and GIT both have the facility:
git -global option command [-sub option] [...]
Here, you run one getopts loop to get the global options; pick up the mandatory arguments; and run a second getopts loop to get the sub-options (and maybe run a final loop over the 'file name' arguments).
Isn't life fun?
And I heard a completely opposite thing, that you shouldn't use getopt, but the getopts builtin.
Cross-platform getopt for a shell script
Never use getopt(1). getopt cannot handle empty arguments strings, or
arguments with embedded whitespace. Please forget that it ever
existed.
The POSIX shell (and others) offer getopts which is safe to use
instead.
Here's yet another way to "Option-ize your shell scripts" (whithout using getopt or getopts):
http://bsdpants.blogspot.com/2007/02/option-ize-your-shell-scripts.html

Bash, no-arguments warning, and case decisions

I am learning bash.
I would like to do a simple script that, when not arguments given, shows some message. And when I give numers as argument,s depending on the value, it does one thing or another.
I would also like to know suggestions for the best online manuals for beginners in bash
Thanks
if [[ $# -eq 0 ]] ; then
echo 'some message'
exit 0
fi
case "$1" in
1) echo 'you gave 1' ;;
*) echo 'you gave something else' ;;
esac
The Advanced Bash-Scripting Guide is pretty good. In spite of its name, it does treat the basics.
If only interested in bailing if a particular argument is missing, Parameter Substitution is great:
#!/bin/bash
# usage-message.sh
: ${1?"Usage: $0 ARGUMENT"}
# Script exits here if command-line parameter absent,
#+ with following error message.
# usage-message.sh: 1: Usage: usage-message.sh ARGUMENT
Example
if [ -z "$*" ]; then echo "No args"; fi
Result
No args
Details
-z is the unary operator for length of string is zero.
$* is all arguments.
The quotes are for safety and encapsulating multiple arguments if present.
Use man bash and search (/ key) for "unary" for more operators like this.
Old but I have reason to rework the answer now thanks to some previous confusion:
if [[ $1 == "" ]] #Where "$1" is the positional argument you want to validate
then
echo "something"
exit 0
fi
This will echo "Something" if there is no positional argument $1. It does not validate that $1 contains specific information however.
If there is not only 1 argument, then print usage and exit
if [[ $# != 1 ]] ; then
echo 'USAGE: bin/siege COOKIE'
exit 0
fi

Resources