shell中如何生成随机数?

简介: shell中如何生成随机数?
########################
# Generate a random string
# Arguments:
#   -t|--type - String type (ascii, alphanumeric, numeric), defaults to ascii
#   -c|--count - Number of characters, defaults to 32
# Arguments:
#   None
# Returns:
#   None
# Returns:
#   String
#########################
generate_random_string() {
    local type="ascii"
    local count="32"
    local filter
    local result
    # Validate arguments
    while [[ "$#" -gt 0 ]]; do
        case "$1" in
        -t | --type)
            shift
            type="$1"
            ;;
        -c | --count)
            shift
            count="$1"
            ;;
        *)
            echo "Invalid command line flag $1" >&2
            return 1
            ;;
        esac
        shift
    done
    # Validate type
    case "$type" in
    ascii)
        filter="[:print:]"
        ;;
    alphanumeric)
        filter="a-zA-Z0-9"
        ;;
    numeric)
        filter="0-9"
        ;;
    *)
        echo "Invalid type ${type}" >&2
        return 1
        ;;
    esac
    # Obtain count + 10 lines from /dev/urandom to ensure that the resulting string has the expected size
    # Note there is a very small chance of strings starting with EOL character
    # Therefore, the higher amount of lines read, this will happen less frequently
    result="$(head -n "$((count + 10))" /dev/urandom | tr -dc "$filter" | head -c "$count")"
    echo "$result"
}

c8d5663c7af0483cb6cafc3c4505df83.pngtr 中-d -c

# 字符集补集,从输入文本中将不在补集中的所有字符删除
echo aa.,a 1 b#$bb 2 c*/cc 3 ddd 4 | tr -d -c '0-9 \n'

5aeda60eccbf48378f9a3b5395c7c87e.png

目录
相关文章
|
2月前
|
Shell
Shell函数
Shell函数
35 1
|
7月前
|
存储 Shell
shell函数介绍
shell函数介绍
41 2
|
7月前
|
Shell Linux C#
shell(十)函数
函数:一段代码的集合。 Linux系统shell编程中也是有函数这个概念的。这个东西我们也就很熟悉了。在我接触的其他编程语言中,都是有函数这个概念的,就是有些语言中的叫法不同,有的叫函数,有的叫方法。 一:系统函数: Shell编程中为我们定义了很多系统函数。所谓的系统为我们定义的系统函数,其实就是我们之前学到的系统命令。比如:date,basename,dirname 1:date 这里首先使用date命令做一下测试,也很简单,正常我们的服务器日志要求是一天生成一个文件。这就涉及到命名的问题,这里使用date就很合适。 编辑 she.sh文件
57 0
|
12月前
|
Shell
|
Shell
shell函数
shell函数
46 0
|
弹性计算 Shell Linux
3天玩转shell--9.shell中的数字及时间运算
本文将通过shell代码示例,简单通俗的讲解shell。通过执行代码和运行结果反向掌握shell编程方法。准备一台低配的阿里云ECS Linux环境,跟着教程走起,本文比较适合shell小白。
|
Shell
shell脚本比较运算
数值运算符
103 0
|
Shell
Bash shell 中,三种子 shell 实践
Bash shell 中,三种子 shell 实践 一 背景 让我们先来看一下下面这个简单的例子: #!/bin/bash #=============================================================================== # FILE: process_test.
806 0
|
Shell 应用服务中间件
shell之函数
函数语法 image.png 函数样例 image.png 函数调用 image.png 系统文件中的函数 vi /etc/init.
951 0