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 renamed" done > ~/Test/log.txt I've done two things here:
The redirection to the log file would truncate the log file in each iteration, so I've moved it to the end of
doneinstead so that it redirects all standard output of the loop.If the pattern does not match any filenames, it will remain unexpanded by default. I detect this with a
-etest and output a special message. Then Ibreakout 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 renamed\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").
Both alternatives above may also run with /bin/sh rather than /bin/bash.
Another alternative, if you want to write more of a "report":
#!/bin/bash shopt -s nullglob xfr_files=( "$HOME/Test/Files"/*.xfr ) for file in "${xfr_files[@]}"; do mv "$file" "${file%.xfr}" done printf '%d files renamed\n' "${#xfr_files[@]}" if [ "${#xfr_files[@]}" -gt 0 ]; then printf '\t%s\n' "${xfr_files[@]}" fi This sets the nullglob shell option in bash which makes patterns expand to nothing if there are no matches. It then writes out the number of files renamed and if this number is greater than zero, it also lists the filenames with a tab indent.