将多个参数传递给脚本linux

时间:2017-05-24 12:22:50

标签: linux bash sh

我有以下代码,它应该将文件名作为参数,并将它们发送到我的电子邮件地址,该地址来自用户名:

#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. roman@workemail.com

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

但是,当传递多个参数时,只有最后提到的文件名作为附件发送。如何将多个参数传递到$ filename变量中,所有变量都附加在&#34; -a&#34;?

1 个答案:

答案 0 :(得分:2)

由于您使用的是bash,因此正确使用的是数组。

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

mailx "${attachments[@]}" -s "Subject" "$u3" < /dev/null