简体   繁体   中英

email shell script part 2

I'm creating a shell script that takes in user input and text's people using the mail function. I am looking to make it more advanced. Right now it just text's one person at a time, I want it to have the ability to text multiple people or even everyone with a user input of 'All'.

#!/bin/sh

# Prefix the numbers with something
number_Joe=8881235555
number_Bob=8881235556

echo "Who do you want to text?:(i.e. Joe, Bob, etc)"
read name
echo "What do you want to say?:"
read quote

# Remove any dangerous characters that the user enters
sanitized=$(printf "%s" "$name" | tr -cd 'a-zA-Z')

#Look up by evaluating e.g. "number=$number_Joe"
eval "number=\$number_$sanitized"

if [ "$number" ] 
then
    echo "texting $name ($number) with $quote"
    printf "%s\n" "$quote" | mailx -s "Text Message via email" "$number@txt.att.net"
else
    echo "Unknown user"
    exit 1
fi

Also, is there a cleaner method of bringing in a external txt file that houses the numbers instead of the script? (note: we still have bash <4, thus why I'm not using a associative array)

Here's a rewrite. Should work fine in bash3.

#!/bin/bash

# Prefix the numbers with something
names=()
names+=(Joe); numberJoe=8881235555
names+=(Bob); numberBob=8881235556

domain=txt.att.example.com

usage () {
    echo "usage: $(basename $0) names message ..."
    echo "where: names is a comma-separated list of names (no spaces)"
    echo
    echo "example: $(basename $0) Jim,Fred hello lads, this is my message"
}

while getopts ":hl" opt; do
    case $opt in
        h) usage; exit ;;
        l) IFS=,; echo "known names: ${names[@]}"; exit ;;
    esac
done
shift $((OPTIND - 1))

if (( $# < 2 )); then
    usage
    exit
fi

IFS=, read -ra usernamelist <<<"$1" 
shift
message="$*"

# validate names
namelist=()
for name in "${usernamelist[@]}"; do
    if [[ " ${names[@]} " == *" $name "* ]]; then
        namelist+=("$name")
    else
        echo "unknown name: $name" >&2
    fi
done
if (( ${#namelist[@]} == 0 )); then
    echo "no valid names given" >&2
    exit 1
fi

# generate the recipient list
echo "texting '$message' to:"
recipients=()
for name in "${namelist[@]}"; do
    numvar="number$name"
    echo "   $name -> ${!numvar}"
    recipients+=( "${!numvar}@$domain" )
done

# send it
printf "%s\n" "$message" | mailx -s "Text Message via email" "$(IFS=,; echo "${recipients[*]}")"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM