I have just started learning bash and am working on my first small project. I am trying to use an array as a argument to attach files using mail however though a file exists in my directory mail is returning : No such file or directory
I have tried manually typing the commands in via shell specifying the filename without the usage of arrays and this works without any errors.
Here is the code:
In my directory say for instance I have File1, File2, File3. The file names will always begin with the name "File" however the numbers for each file will differ.
First I define an array with the File numbers:
esend=(1 2 3)
Then I loop over each iteration of the array and create a copy of this array appending each iteration with -a [Filename]
# Loop over array and build the arguments for mailx.
for i in "${esend[@]}"
do
# for each iteration append onto array with -a [filename]
mailarray=( "${mailarray[@]}" "-a $(find -name "File$i" | sed "s|^\./||")" )
done
The values in the each index should be "-a File1 -a File2 -a File3" and now my plan is to use this as the arguments for mail
# "${mailarray[@]}" will contain the arguments ( -a File1 -a File2 -a File3 )
echo "File being sent from mail" | mailx "${mailarray[@]}" -s "Script.sh" -r "[email protected]" [email protected]
The actual result is that mail returns File1: No such file or directory found.
Either I am doing something wrong here, or simply we cannot use this approach?
In Your case You need to de-quote Your array variable mailarray in order to get represented as arguments otherwise it is represented as one string in Bash:
mailx ${mailarray[@]} -s "Script.sh" -r "[email protected]" [email protected]
But be aware that this is dangerous way e.g. any files with special characters won't be handled correctly. In addition You are also not handling multiple outputs of find. Also removing path with sed is not necessary, rather better to keep.
I would rather rewrite to something like this (supports multiple find outputs while loop, supports special characters -print0, exits with return code of mailx):
#!/bin/bash
mailargs=()
for ((i=1;i!=4;i++))
do
while IFS= read -r -d $'\0'
do
mailargs+=("-a" "${REPLY}")
done < <(find ./ -type f -name "File${i}" -print0)
done
echo "File being sent from mail"
mailx "${mailargs[@]}" -s "Script.sh" -r "[email protected]" [email protected]
exit $?
Consider also option e.g. to tar multiple files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With