在写前一篇文章的时候,发现做的有点复杂了,其实有更好的办法。 不必生成一个行号的文件, 文本文件本身就有行的概念,得到随机数后,直接取那行不就行了吗。 这是新版本,更短更简单:
#! /bin/sh # randomly choose a file # Simpler version, Yuwen Dai, 18 November, 2012 # Initial version, Yuwen Dai, 13 September, 2012 # Add file types here FILE_TYPE="*.mp4 *.flv *.mp3" # Get the total number of files TOTAL=`ls -l $FILE_TYPE|wc -l` TOTAL=$((TOTAL-1)) # Get a random number: [0, TOTAL] R=$((${RANDOM}*${TOTAL}/32767)) # We have to ajust R, for sed uses line number starting from 1 R=$((R+1)) # Get the file name FILE=`ls ${FILE_TYPE} |sed -ne "${R}p"` echo ${FILE} # we got file name, use it whatever you want #exec mplayer "${FILE}"