Creation of a simple script that renames a file picking randomly from a group of files
Solution 1:
You cannot both "rename" a file and "not lose the original", you'll have to copy (man cp
) the randomly selected original file to greetings.ogg
, something like:
# select among 0.ogg .. 9.ogg
cp $(( $RANDOM % 10 )).ogg greetings.ogg
Read man bash
, you might want to initialize $RANDOM
.
Solution 2:
If your files are not necessarily named with a simple arithmetic scheme amenable to the use of the shell's $RANDOM
variable, then another option is to use shuf
:
shopt -s extglob
cp -- "$(printf '%s\n' !(greeting).ogg | shuf -n 1)" greeting.ogg
The ksh-style extended glob !(greeting).ogg
avoids copying the existing file to itself - you could avoid that by copying the file to a different directory.
Solution 3:
A more elegant solution (as already suggested in comments by both Ginnungagap and James S.), would be to use symlinks, like so:
#!/bin/bash
# Select among ten files at random and make a renamed copy inside /home/$user
ln -sf $(( $RANDOM % 10)).mp3 /home/x/greetings.mp3
Note: ln
is both faster and more efficient, in terms of disk usage, than cp
.
Note the use of the -f
option to overwrite any link to a previous greeting sound - see Create symlink - overwrite if one exists.
Alternatively, avoiding the use of $RANDOM
(and bash
) altogether, and using shuf
instead:
#!/bin/sh
rand=`shuf -i 1-10 -n 1`
ln -sf ${rand}.mp3 /home/x/greetings.mp3
The use of shuf
is taken from this answer to Generate random numbers in specific range).