Score:3

all files in the folder disappeared because of a typo while using `mv`

jp flag

I am new to bash and I was trying to rename all files in a directory to their md5 checksum in the following way.

r@r:~g$ sh
$ for F in *; do
>     mv "$F" "$(md5sum "$i")"
> done
r@r:~/g$ ls
'd458d56dd4ab8c2b335da66e0bcab924  nRUNO5wt3JRN3pBt.mp4'

I made a typo and the line mv "$F" "$(md5sum "$i")" should be mv "$F" "$(md5sum "$F")" if I'm not wrong. Now all the files in the folder are missing but one.

Are the files deleted or moved somewhere? Is there any way to restore them?

When I try to reproduce the situation in a folder with the file "1.png" in it, the following happens.

r@r:~/a$ sh
$ for F in *; do
>     mv "$F" "$(md5sum "$i")"
> done
md5sum: '': No such file or directory
mv: cannot move '1.png' to '': No such file or directory
cn flag
Unless you have a backup, those files cannot be restored. Each file was overwritten by the subsequent one, leaving only the last.
Score:5
it flag

Probably not. Consider how your loop "works", and which mv commands are executed.

For the first file, you executed

mv the_file "$(md5sum $i)"

but, since "$(md5sum "$i")" does NOT change as you loop, the command for the next file is:

mv the_2nd_file "$(md5sum "$i")"

replacing the first file. The first file is deleted, and its disk blocks are marked "free".

The same thing happens to the 3rd through Nth files. All that's left is the LAST file, now named "$(md5sum "$i")".

Do you have backups?

When writing powerful/dangerous commands to be applied to a bunch of files, use echo:

for f in * ; do
 echo mv $f "$(md5sum "$i")"
done

would have shown your error.

BTW, upper case [A-Z] variable names are traditionally used to communicate with applications. If you use lower case [a-z] names in your scripts, you'll never overlap.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.