I have lots of files that need an extension appended to them but they are in a directory with lots of subdirectories. Currently the files have no extension at all. How would I rename just the files but not rename any of the directories or subdirectories?


Iterate all and test whether it's a regular file or not.

for file in ./*; do
    [[ -f $file ]] && mv "$file" "$file.ext"

In case you need to avoid adding extension on files that already have it:

for file in ./*; do
    if [[ -f $file && $file != *.ext ]]; then
        mv "$file" "$file.ext"
  • 1
    For some reason this script ignores file names that include spaces in them, is there anyway to include them as well? – Kevin Jun 20 '12 at 19:00
  • @Kevin, it should handle them just fine. Did you modify anything? If you remove any of the "-quotes, it will fail on filenames containing whitespace or other syntactical characters. – geirha Jun 21 '12 at 0:02
  • @geirha shouldn't -f $file have quotes as well ? – Sergiy Kolodyazhnyy Jun 1 '15 at 10:31
  • @Serg With [ ... ] instead, then quotes would be necessary, but [[ ... ]] is a shell keyword and is parsed differently, so quotes there are optional. See BashFAQ 31 for more on the differences. – geirha Jun 1 '15 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.