Search code examples
bashbrace-expansion

mv brace expansion with globbing in script


I'm trying to move photos to a different directory. It works great when I run mv from the command line (in bash and zsh):

mv './DSC_{2385..2387}.NEF*' ./new/STACK_2385-2387

I wrote this bash script that moves a series of photos to a different directory.

But not if I run it from a script:

#/bin/bash
set -x
read START
read END
PREFIX="STACK"
DIRNAME=$PREFIX\_$START-$END
mkdir ./new/$DIRNAME
mv ./DSC_{$START..$END}.NEF* ./new/$DIRNAME

.

$./script.sh
mv ./DSC_{$START..$END}.NEF* ./new/$DIRNAME
+ mkdir ./new/STACK_2385-2387
+ mv './DSC_{2385..2387}.NEF*' ./new/STACK_2385-2387
mv: cannot stat './DSC_{2385..2387}.NEF*': No such file or directory

./new/STACK_2385-2387 is being created. The relevant *.NEF raws and *.NEF.xmp sidecar files also exist, including 2385, 2386, and 2387, so it's not an issue there.


Solution

  • you can only do variable brace expansion with evil eval as in this example

    $ a=1; b=10; eval echo {$a..$b}
    1 2 3 4 5 6 7 8 9 10
    

    so you need to change mv command to

    $ eval mv ./DSC_{$START..$END}.NEF* ./new/"$DIRNAME"
    

    perhaps double quote the variables as well.