How to move and rename a file with random characters in shell?

834 Views Asked by At

I have this file:

/root/.aria2/aria2.txt

and I want to move it to:

/var/spool/sms/outgoing/aria2_XXXXX

Note that XXXXX are random characters.

How do I do that using only the facilities exposed by the openwrt (a GNU/Linux distribution for embedded devices) and the ash shell?

3

There are 3 best solutions below

2
On

A simple way of generating a semi-random number in bash is to use the date +%N command or the system provided $RANDOM:

rn=$(date +%N)   # Nanoseconds
rn=${rn:3:5}     # to limit to 5 digits

or, using $RANDOM, you need to check you have sufficient digits for your purpose. If 5 is the number of digits you need:

rn=$RANDOM
while [ ${#rn} -lt 5 ]; do
    rn="${rn}${RANDOM}"
done
rn=${rn:0:5}

To move while providing the random suffix:

mv /root/.aria2/aria2.txt /var/spool/sms/outgoing/aria2_${rn}
0
On

On systems with /dev/random you can obtain a string of random ASCII characters with something like

dd if=/dev/random count=1 |
tr -dc ' -~' |
dd bs=8 count=1

Set the bs= in the second instance to the amount of characters you want.

The probability of getting the same result twice is very low, but you have not told us what is an acceptable range. You should understand (or help us help you understand) what is an acceptable probability in your scenario.

1
On

Use the tempfile command

mv aria2.txt `tempfile -d $dir -p aria2`

see man tempfile for the gory details.