Reputation: 320
I am trying to code an error for a function that requires multiple arguments.
example:
myfunction arg1 arg2 arg3 arg4
If any of these arguments are null I want to trow the user a syntax error.
Without writing the individual arguments I tried:
# Error Checking
for i in "{1.4}"
do
# Check for null values of Bash variables:
[[ -z $"$i" ]] && {
printf "Syntax Error: Missing Operator see:\nmyfunction --help\n"
exit
}
done
-and-
# Error Checking
for i in ${1..4}
do
# Check for null values of Bash variables:
[[ -z $i ]] && {
printf "Syntax Error: Missing Operator see:\nmyfunction --help\n"
exit
}
done
Is what I am trying to do possible with a for loop?
Any help would be much appreciated.
Thanks in advance!
Also tried the following before I started messing with quotes and dollar signs:
# Error Checking
for i in {1..4}
do
[[ -z $"$i" ]] && {
printf "Syntax Error: Missing Operator see:\nansi-color --help\n"
exit
}
done
Upvotes: 1
Views: 123
Reputation: 347
Personally, I'd use a bash array and then check its length:
args=($*)
echo ${#args[*]}
But you can do this:
myfunc() { for i in {1..4}; do
if [[ -z ${!i} ]]; then
echo error at $i
return -1
fi
done
...do other stuff
}
Upvotes: 0
Reputation: 320
Caleb Adams pointed out that I could try something like this:
# Error Checking
[[ $# != 4 ]] && {
printf "Syntax Error: Missing Operator see:\n\tansi-color --help\n"
exit
}
Upvotes: 0
Reputation: 1184
There are several ways to tackle this:
die () { echo "$@" >&2; exit 1; }
myfn () {
[[ $# == 4 ]] || die 'wrong number of args'
for d in "$@"; do [[ $d ]] || die 'null arg'; done
}
myfn2 () {
[[ $# == 4 ]] || die 'wrong number of args'
for ((i = 1; i <= $#; i++)); do
[[ ${!i} ]] || die 'null arg'
done
}
The "$@"
is probably more idiomatic. The indirection with !
is very handy though not common.
Upvotes: 2