[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: (v) ugly (and simple) bash script...



On 5/21/2022 3:55 PM, Greg Wooledge wrote:
On Sat, May 21, 2022 at 10:08:42AM +0100, Morgan Read wrote:
I've come up with:
`cd ~/Maildir/new/; for f in *; do mv -- "$f" ~/Maildir/cur/"${f%}.eml"; cd
-; done`

You aren't checking whether the first cd succeeds.  If it fails for any
reason, you're going to end up moving file(s) out of wherever you happen
to be at the time.

You also don't want that "cd -" to be *inside* the loop.  If there's more
than one file in ~/Maildir/new/, you're going to move the first one, then
cd back to where you were, then try to move the second file by its
relative name from the directory you changed *back* to.  There probably
won't be a file by that name in the original directory, so it'll probably
give an error... but if it doesn't, then you've screwed up big time.

If this is a script, you don't need the "cd -" at all.  Just let the
script exit, and it won't matter what directory it ended in.

Finally, ${f%} is just a fancy way of writing $f.  You're literally saying
"take the value of $f but remove the empty string from the end of it".

#!/bin/sh
cd ~/Maildir/new/ || exit 1
for f in *; do
   mv -- "$f" ../cur/"$f.eml"
done


+1 for readability in a script.

I would also bail out if the mv command fails:

for f in *; do
    mv "$f" ../cur/"${f}.eml" || exit $?
done

--
John Doe


Reply to: