Home > front end >  bash/ksh add if no argument given echo add value please
bash/ksh add if no argument given echo add value please

Time:04-24

I have this code for executing a single command using a number of different arguments:

for ((i = $#; i > 0 ; i--)) ; do
    grep -w -- "$1" codelist.lst || echo "'$1' not found"
    shift
done

This script gives me, for each argument, the correct output of either the lines containing the argument, or an indication that no lines were found.

What I wish to add is a message if the user provided no arguments, such as "Please insert a value". How do I do that?

CodePudding user response:

You can simply check $# before attempting to run the loop:

if [[ $# -eq 0 ]] ; then
    echo "Please insert a value."
else
    for ((i = $#; i > 0 ; i--)) ; do
        grep -w -- "$1" codelist.lst || echo "'$1' not found"
        shift
    done
fi

A zero value means that no arguments were provided.


An alternative form if you value simplicity of code is to realise that zero will also cause the loop body not to run even if the loop itself is executed, so you could do something like:

[[ $# -eq 0 ]] && echo "Please insert a value."
for ((i = $#; i > 0 ; i--)) ; do
    grep -w -- "$1" codelist.lst || echo "'$1' not found"
    shift
done
  • Related