tags:

views:

45

answers:

3

Hi,

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

A: 
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.

Thomas
RE: "exit 0". I don't know if exiting the script was what he had in mind. But yes, that's an excellent guide.
Trampas Kirk
I interpreted "and" as "otherwise", assuming that the message would be some help text. But I'm sure Werner is able to figure out what that line does and whether he wants it :)
Thomas
thanks, of course!and last thing, how can i turn off error messages ib the script, so they are not shown to the shell?
Werner
You mean the errors coming out of a particular program you're calling? You can put `> /dev/null` and/or `2> /dev/null` after that to send its standard output and/or standard error streams into oblivion.
Thomas
You can also do `exec 2>/dev/null` to nuke standard error globally, for all commands in the script. Not that I think that's a good idea, though.
Idelic
A: 

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.

Trampas Kirk
A (minor) problem with this is that it doesn't distinguish between passing no arguments and passing an empty string as argument. That may be important in some contexts. Using [ $# -eq 0 ] one can handle both cases properly.
Idelic
Ah, the subtleties of (ba)sh programming... This is why I hate it.
Thomas
A: 

you might also want to look at getopts

ghostdog74