How to find out if $1 is defined using sh

How to find out if $1 is defined using sh

am 13.09.2007 18:18:19 von mrstephengross

I'm using sh, and I want to find out if a commandline argument ($1,
that is) has been specified. I can't seem to find the right syntax for
it... any ideas?

Thanks,
--Steve

Re: How to find out if $1 is defined using sh

am 13.09.2007 18:32:44 von Tweedale

On 13 Sep 2007 at 16:18, mrstephengross wrote:
> I'm using sh, and I want to find out if a commandline argument ($1,
> that is) has been specified. I can't seem to find the right syntax for
> it... any ideas?

[ "$1" ] && echo "There was an argument."

--
email: echo t.adllkhsl@iypzavs.hj.br | tr a-gh-pq-z t-za-ij-s

Re: How to find out if $1 is defined using sh

am 13.09.2007 18:33:08 von Joachim Schmitz

"mrstephengross" schrieb im Newsbeitrag
news:1189700299.933919.163080@k79g2000hse.googlegroups.com.. .
> I'm using sh, and I want to find out if a commandline argument ($1,
> that is) has been specified. I can't seem to find the right syntax for
> it... any ideas?

$# will tell you the number of args

Bye, Jojo

Re: How to find out if $1 is defined using sh

am 13.09.2007 19:23:38 von mrstephengross

> [ "$1" ] && echo "There was an argument."


Thanks!

--Steve

Re: How to find out if $1 is defined using sh

am 13.09.2007 19:38:31 von Stephane CHAZELAS

2007-09-13, 16:32(+00), Tweedale:
> On 13 Sep 2007 at 16:18, mrstephengross wrote:
>> I'm using sh, and I want to find out if a commandline argument ($1,
>> that is) has been specified. I can't seem to find the right syntax for
>> it... any ideas?
>
> [ "$1" ] && echo "There was an argument."

No, that's wrong.

First, the prefered way (because it's clearer and not subject to
issues on old shells) to test whether a string is non-empty is

[ -n "$1" ], not [ "$1" ]

And then it tests whether "$1" expands to a non-empty string,
not whether it is supplied.

Especially, if an empty argument is supplied, the above will
claim there is no argument.

The correct way is to use "$#"

[ "$#" -gt 0 ] && echo "There was at least an argument"

And to test whether arbitrary variables (not only positional
parameters) are defined:

[ "${var+defined}" = defined ]

or [ -n "${var+.}" ] (shorter but less legible).

--
Stéphane

Re: How to find out if $1 is defined using sh

am 13.09.2007 19:51:47 von Gretch

In news:slrnfeiphb.9of.seesig@math-pc325.maths.bris.ac.uk,
Tweedale wrote:

>> I'm using sh, and I want to find out if a commandline argument ($1,
>> that is) has been specified. I can't seem to find the right syntax
>> for it... any ideas?
>
> [ "$1" ] && echo "There was an argument."

[ "$1" ] && echo -e "There was an argument.\nWas not!\nWas too ... and I'm
telling!"