Robert J
Robert J

Reputation: 320

For loop for shell Variables

Overview:

I am trying to code an error for a function that requires multiple arguments.

If any of these arguments are null I want to trow the user a syntax error.

Attempts:

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

Attempted syntax check:

enter image description here enter image description here

Question:

Is what I am trying to do possible with a for loop?

Any help would be much appreciated.

Thanks in advance!

Edit:

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

Answers (3)

nortally
nortally

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

Robert J
Robert J

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

dan4thewin
dan4thewin

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

Related Questions