Bash, no-arguments warning, and case decisions

Bash

Bash Problem Overview


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

Bash Solutions


Solution 1 - Bash

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.

Solution 2 - Bash

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

Solution 3 - Bash

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.

Solution 4 - Bash

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOpen the wayView Question on Stackoverflow
Solution 1 - BashThomasView Answer on Stackoverflow
Solution 2 - BashPatView Answer on Stackoverflow
Solution 3 - BashTrampas KirkView Answer on Stackoverflow
Solution 4 - BashRyan SmithView Answer on Stackoverflow