0

I'm using two short bash scripts for renaming all *.dds files in all directories.

The first one:

#!/bin/bash
j=39;
for i in *.dds;
do let j+=1;
mv $i 0150$j.dds;
done

The second one:

CURDIR=`pwd`
for d in $(find . -type d);
do
    cd $CURDIR/"$d"
    $CURDIR/3_rename.sh
done

I'm running the second one and obtain:

mv: cannot stat '*.dds': No such file or directory

But *.dds files are renamed correctly. I would like to understand my mistake which leads to the error.

3
  • You can try to debug your script by running it using bash -x script.sh, and see what it actually does.
    – annahri
    Commented Jul 27, 2023 at 1:53
  • Is the first script one the 3_rename.sh that the second one runs? If so, that's what I'd expect to happen if it runs in a directory with no .dds files. BTW, there are some situations where the first script will accidentally delete files due to naming conflicts (especially if it's run multiple times in a directory with a large number of .dds files). You should use mv -i or mv -n for mass renames like this to prevent accidents. Commented Jul 27, 2023 at 4:05
  • @GordonDavisson, yes, the first script is 3_rename.sh and I run it in a directory with no .dds files. Commented Jul 27, 2023 at 7:52

1 Answer 1

1

In your rename script, the *.dds glob expands to the file names in the current directory that end with a .dds extension: 1.dds, 2.dds and so on.

The problem here is a directory that does not have any files ending with a .dds extension, so there is nothing for the glob to match. In this scenario, the default behaviour of bash is to return the literal string '*.dds'. This gets passed on to the mv command, which prints an error as no such file exists.

The shell option 'nullglob' can adjust this behaviour. With 'nullglob' turned on, non-matching globs will disappear instead of returning the literal string. With zero arguments, the for loop will skip the empty directory.

You can turn on 'nullglob' just before your loop:

shopt -s nullglob
for i in *.dds;
...

More details and examples are available here: https://mywiki.wooledge.org/glob#nullglob . Do note the warning and portability sub-sections, as they highlight some of the concerns in using 'nullglob'.

1
  • Thank you. Yes, I run it in a directory with no .dds files. .dds files are only in subdirectories. Commented Jul 27, 2023 at 7:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .