首页 > 其他 > 详细

shell 获得一定长度的随机字符串

时间:2014-02-18 14:21:42      阅读:457      评论:0      收藏:0      [点我收藏+]

#! /bin/bash

#设置全局变量,作为函数的返回值
export randresult

function GetRandNum()
{
  srcstring=$1
  length=$2
  #注意这里一定要设置成局部的,否则会与后面的冲突
  local index=0
  while [ $index -ne $length ]
  do
   #获得时间种子,现在到1970年的秒数
   randtime=$(date +%s)
   #因为同一秒相同的可能,再加上系统随机函数,不直接用系统随机函数,因为只有5位
   randtime=$[ $randtime + $RANDOM ] 
   ((randindex=randtime%length))
   #截取字符串
   randchar=${srcstring:$randindex:1} 
   #字符串链接
   randresult=$randresult$randchar
    ((index++))
  done  
  return $randresult
}

read -p "please input the source string" src
read -p "please input the length " length
index=0
while [ $index -ne 100 ]
do
   #取消变量定义
   unset randresult
   #函数调用    
   GetRandNum $src $length
   echo "the final result is $randresult\n"
   ((index++))
done


 

本文出自 “风清扬song” 博客,请务必保留此出处http://2309998.blog.51cto.com/2299998/1359862

shell 获得一定长度的随机字符串

原文:http://2309998.blog.51cto.com/2299998/1359862

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!