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

目录
相关文章
|
5月前
|
存储 前端开发 JavaScript
shell(七)数组
数组可以存储多个数据,这个东西是很重要的,其他一些高级语言类似PHP、javascript等语言都是支持多维数组的。Shell编程只支持一维数组。 Shell编程的数组和PHP的数组类似,声明的时候不需要指定大小。也可以使用下标来访问数组中的元素。 Shell 数组用括号来表示,元素用"空格"符号分割开,语法格式如下:
39 0
|
弹性计算 Shell Linux
3天玩转shell--9.shell中的数字及时间运算
本文将通过shell代码示例,简单通俗的讲解shell。通过执行代码和运行结果反向掌握shell编程方法。准备一台低配的阿里云ECS Linux环境,跟着教程走起,本文比较适合shell小白。
|
Shell
shell脚本比较运算
数值运算符
96 0
|
Shell
Bash shell 中,三种子 shell 实践
Bash shell 中,三种子 shell 实践 一 背景 让我们先来看一下下面这个简单的例子: #!/bin/bash #=============================================================================== # FILE: process_test.
797 0
|
Shell
shell之数组
数组可以存放多个值,bash shell只支持一维数组,初始化时不需要指定数组大小。下标从0开始。 语法 Shell 数组用括号来表示,元素用"空格"符号分割开 array_name=(value1 .
877 0