I am trying to move specific file names all at once from one directory to other using single command line. I have captured the file names (not with full path) in a variable as shown below, it may have 100 to 1000 files names.
var="M1.txt,A2.dat,T300.log"
I tried following command its working mv /home/rrajendr/test1/{M1.txt,A2.dat,T300.log} /home/rrajendr/test2/
Same is not working if it's parameterized mv /home/rrajendr/test1/{"$var"} /home/rrajendr/test2/
Error mv: cannot stat ‘/home/rrajendr/test1/{M1.txt,A2.dat,T300.log}: No such file or directory
Its looking for a filename as exactly like this "{M1.txt,A2.dat,T300.log}" as is, its not interpreting as individual file name. Something is missing here, please let me know
I tried following option but didn't worked
mv /home/rrajendr/test1/echo $var
-t /home/rrajendr/test2/
mv /home/rrajendr/test1/{$var}
mv /home/rrajendr/test1/{echo $var
}
Reason I am looking this option
If you are creating the file list and know there are no funny characters in the list, I'd use eval
:
cmd="mv /home/rrajendr/test1/{$var} /home/rrajendr/test2"
eval $cmd
or even
eval "mv /home/rrajendr/test1/{$var} /home/rrajendr/test2"
Note that brace expansion is not (yet) a POSIX shell feature as of 2023. This will only work if your sh is bash or zsh or any other shell supporting brace expansion.
I'd say that the proper way to do this, with much less opportunities to break, is to loop or use xargs
. Why do you want to avoid that? Moving files is never a bottle neck.