Skip to main content
1 of 7
Kusalananda
  • 356.1k
  • 42
  • 737
  • 1.1k

Modifying your first script a tiny bit:

#!/bin/bash for file in ~/Test/Files/*.xfr do if [ ! -e "$file" ]; then echo 'no files were renamed' break fi mv "$file" "${file%.xfr}" echo "$file has been resent" done > ~/Test/log.txt 

I've done two things here:

  1. The redirection to the log file would truncate the log file in each iteration, so I've moved it to the end of done instead so that it redirects all standard output of the loop.

  2. If the pattern does not match any filenames, it will remain unexpanded by default. I detect this with a -e test and output a special message. Then I break out of the loop.

Alternative:

#!/bin/bash for file in "$HOME/Test/Files"/*.xfr do if [ -e "$file" ]; then mv "$file" "${file%.xfr}" printf '%s has been resent\n' "$file" else echo 'no files were renamed' fi done >"$HOME/Test/log.txt" 

Here I've just changed the flow a bit and used $HOME in place of tilde (looks nicer in a script IMHO). I'm also using printf instead of echo as it's generally safer for outputting variable data (see e.g. "https://unix.stackexchange.com/questions/65803").

Kusalananda
  • 356.1k
  • 42
  • 737
  • 1.1k