1

For my homework assignment, I need to send an email out specified email addresses if disk space falls below a certain threshold. I am having issues with passing the email addresses to a variable, however. The user can specify as many email addresses as they like at the command prompt. Also, if they do not include a domain, the email should still send to an "@uml.edu" address.

I am trying to solve the problem of the user entering in an unknown number of email addresses by using an array. I have never really used an array in bash, and I think I might be using incorrect syntax.

I don't know if I necessarily need to use an array to accomplish what I am doing, but it seemed to make the most sense. I have tried using a for loop to accept multiple values, and I am using a case statement to handle whether or not the user included a domain for an email address.

#!/bin/bash

email=()

for {{ x=0; $#<0; x++ ))

   do

      case $1 in

         *@*) email[x]="$1"
         shift ;;

         *) email[x]="${1}@uml.edu"
         shift ;;

      esac

   done

echo ${email[@]}

The above code is basically a test case that I would work into my main code once I get it working. The expected results would be the user could enter in one or more email addresses at the command line and then they would be displayed via the echo command.

1
  • 1
    (Why that does work? A for loop iterates over "$@", the list of command-line arguments, by default; and arr+=( "item1" "item2" ) lets you append one or more items without needing to track index numbers). Commented Apr 4, 2019 at 21:23

1 Answer 1

1

Use += to append to an array, like this:

array+=(foo bar baz)

That'll let you get rid of the x variable. You can also loop over "$@" without having to shift arguments off.

for arg in "$@"; do
  case $arg in
    *@*) email+=("$arg");;
    *)   email+=("[email protected]");;
  esac
done

And when in doubt, quote your variable expansions.

echo "${email[@]}"

(It's not needed in case $arg in above. But it doesn't hurt if you do quote it there.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.