我想生成一個隨機數,然後使用該隨機數來抓取目錄中的相應文件,這將隨後創建音樂歌曲的隨機播放列表。我採用3個參數,音樂路徑,新播放列表的名稱以及播放列表中要播放的歌曲數量。出於某種原因,在while循環它複製多個文件,而不是僅僅是第n個隨機文件的每一次迭代試圖將目錄中的第n個文件複製到另一個文件夾
#!/bin/bash
#accepts 3 arguments path to music, name of the new playlist, and amount of songs you want in the playlist
path_to_music=$1;
playlistname=$2;
count=$3;
#finds number of songs in directory, allows for more effective randomness
#cd to the path where music is
if [ -d "$path_to_music" ];
then
eval cd $path_to_music
numOfFiles=$(find . -type f | wc -l)
else
echo "Directory does not exist, enter correct path."
read path_to_file
fi
ran=$[ ($RANDOM % 5) + 1 ]
let ran=numOfFiles-ran;
#make new folder where music is, will contain random songs (new playlist)
mkdir $playlistname
i=1
while : #while loop finds a random song and copies it to folder created, $cnt is randomly generated so songs are random
do
if [ "$i" -ne "$count" ];
then
cnt=$[ ($RANDOM % 34) + 1 ]
let "cnt*=(-1)"
find -type f | head $cnt tail $cnt | xargs -I % cp % $path_to_music/$playlistname ;
let "i+=1"
echo $i
else
break;
fi
done;
'head $ cnt tail $ cnt'在兩者之間缺少'|'。 'eval cd $ path_to_music'是* evil *。只要放下'eval',引用變量並且用'〜'住不起作用。 – 2014-12-04 18:51:15