OT: bash help
Fred Smith
fredex at fcshome.stoneham.ma.us
Sat Aug 16 21:58:25 UTC 2014
On Sat, Aug 16, 2014 at 02:44:14PM -0700, Mike Wright wrote:
> Hi all,
>
> I'm trying to write a simple script that if provided an argument,
> uses that, or if nothing is provided, uses a predefined string.
>
> if [ -n $# ]
> then
> WORDS=$1
> else
> WORDS="these are some words"
> fi
> echo $WORDS;
>
> The second case is always comes back "".
>
> But if I write
>
> WORDS='these are some words'
> echo $WORDS
>
> I get the assigned string.
>
> Why doesn't the assignment work when inside an if/then? How do I
> make it work? What's the difference between the case where the
> assignment is inside the if/then and outside the if/then?
This works:
#!/bin/sh
if [ $# -ne 0 ]
then
WORDS=$1
else
WORDS="these are some words"
fi
echo $WORDS
the hashbang line should be used, but doesn't actually change the
output of this script.
"$#" is an integer, not a string, and that it should therefore be tested
as an integer and not a string, hence the if statement being:
if [ $# -ne 0 ]
and you don't NEED the quotes around the literal string, though
it doesn't harm to put them there, perhaps as documentation to make
clear what you intention is.
--
-------------------------------------------------------------------------------
.---- Fred Smith /
( /__ ,__. __ __ / __ : /
/ / / /__) / / /__) .+' Home: fredex at fcshome.stoneham.ma.us
/ / (__ (___ (__(_ (___ / :__ 781-438-5471
-------------------------------- Jude 1:24,25 ---------------------------------
More information about the users
mailing list