× The internal search function is temporarily non-functional. The current search engine is no longer viable and we are researching alternatives.
As a stop gap measure, we are using Google's custom search engine service.
If you know of an easy to use, open source, search engine ... please contact support@midrange.com.



Scott Klement wrote:
Pete,

That code doesn't do what you think it does!!

#!/bin/bash
if [ $1 ] ; then
echo 'Yes!'
else
echo 'No!'
fi


What this is doing is trying to execute $1 as an expression for the
"test" utility to evaluate. If test evaluates to true, it'll print yes,
if not, it'll print no. So this isn't really testing to see if a
parameter is passed! It's evaluating the parameter as an expression!

For example, try this:

$ ./myscript '1 -eq 0'
No!

See what I mean? I *did* pass it a parameter, but it says no. Why?
Because it's running my parameter as an expression. Since 1 is not
equal to 0, it says "No!"

If you just want to test if a parameter is empty, do this instead:

if [ -z "$1" ] ; then
echo 'No!'
else
echo 'Yes!'
fi

I would've given that answer at first if I had known that was what John
was asking. But there are so many things he could've meant...


Alternatively, you could just code:

if [ "$1" ] ; then
echo 'No!'
else
echo 'Yes!'
fi

(Don't forget, the usual shell practice is to quote variable names.)

But, rather than code an optional positional parameter, the more robust
way would be to code a command option. The following example illustrates
the use of the getopts builtin:

#!/bin/bash
while getopts "ab:" opt; do
case $opt in
a)
echo "-a was triggered"
;;
b)
echo "-b was triggered: $OPTARG"
;;
\?)
echo "invalid option: $OPTARG"
;;
esac
done
shift $(($OPTIND - 1))
echo $1 $2 $3 $4

Cheers! Hans


As an Amazon Associate we earn from qualifying purchases.

This thread ...

Follow-Ups:
Replies:

Follow On AppleNews
Return to Archive home page | Return to MIDRANGE.COM home page

This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].

Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.