mardi 4 octobre 2016

Renaming multiple files to a random string renames only one file

Trying to rename files to a random string. I took some code from an answer to this question in order to generate a random string of characters.

#!/bin/bash

chars=( {a..z} {A..Z} {0..9} )

function rand_string {
    local c=$1 ret=
    while((c--)); do
        ret+=${chars[$((RANDOM%${#chars[@]}))]}
    done
    printf '%s\n' "$ret"
}

output=$(rand_string 10)

For practice I made a directory at $HOME/practice with a few plain text files.

/Users/me/practice/testfile1.txt
/Users/me/practice/testfile2.txt
/Users/me/practice/testfile3.txt

When trying to rename these files a random string, instead of getting 3 random names, I am instead left with 1 file renamed to a random string.

for file in $HOME/practice/*
do
    mv "$file" $HOME/practice/"$output" 
done

#result
/Users/me/practice/i6TP3wiMDD

Replacing mv "$file" ~/practice/"$output" with echo "$file" "$output" shows me that the random string is being repeated after every file instead of generating a new random string for every file.

/Users/me/practice/testfile1.txt i6TP3wiMDD
/Users/me/practice/testfile2.txt i6TP3wiMDD
/Users/me/practice/testfile3.txt i6TP3wiMDD

My question is two part:

  1. Why is only 1 file being renamed?
  2. How can I generate a new random string for each file being renamed?

I will also say that the above random character script is above my current understanding. I know that it works for generating random characters. But the inner workings of it are still somewhat unclear to me.




Aucun commentaire:

Enregistrer un commentaire