1

I've got the following code, which is supposed to take filenames as arguments, and send them to my email address, which is derived from a username:

#Email Script from linux
#Define username e.g. pp_roman
u="$USER"

#Remove the pp_ and store to variable e.g. roman

u2=${u#"pp_"}

#Define Email portion

em="@workemail.com"

#Combine the username e.g. [email protected]

u3=$u2$em

#Arguments for script

for FILE1 in "$@"
do
    filename="-a $FILE1"
done

##This returns the full string with $filename variables for arguments, and email from $u3

mailx $filename -s "Subject" $u3 < /dev/null

However when passing multiple arguments, only the last mentioned filename is sent as an attachment. How do I pass multiple arguments into the $filename variable all appended by "-a"?

2
  • What shell are you actually using? bash, ksh, zsh, dash? Or does this need to conform to the POSIX specification for portability? Commented May 25, 2017 at 12:39
  • bash. Currently looking at adding functionality to refuse transfer of files over say 5 meg? don't know how resource intensive mailx is. Commented May 26, 2017 at 13:51

1 Answer 1

2

Since you are using bash, the right thing to use is an array.

attachments=()
for f in "$@"
do
    attachments+=(-a "$f")
done

mailx "${attachments[@]}" -s "Subject" "$u3" < /dev/null
Sign up to request clarification or add additional context in comments.

2 Comments

Would this work for filenames with whitespaces? Previous comment suggested single quotes for '$f', or is this the type input for arrays?
Quoted array expansion using [@] is specifically designed to solve the problem of storing a sequence of values containing whitespace.

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.