linux - Bash - 将函数值设置为变量

标签 linux bash shell debian

<分区>

我有这个代码:

# GENERATE RANDOM PASSWORD
#  $1 = number of characters; defaults to 32
#  $2 = include special characters; 1 = yes, 0 = no; defaults to 1
function randpass() {
  [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
    cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
    echo
}

randpass
randpass 10
randpass 20 0

SSHKEYPASS = randpass 10

我希望能够生成随 secret 码并将其存储为变量。然而,尽管 randpass 工作得很好,但当我尝试将 ```SSHKEYPASS`` 设置为 randpass 的结果时,它不起作用。那么,如何使用我的 randpass 函数在 SSHKEYPASS 变量上生成随 secret 码。

谢谢。

最佳答案

问题是最后一行 SSHKEYPASS=randpass 10 这样做是为了分配 randpass 函数的返回状态而不是 randpass 函数的输出,以便分配 randpass 函数 你必须使用 process substitution 如下

SSHKEYPASS=$(randpass 10)

上述命令将使用 randpass 函数的标准输出填充 SSHKEYPASS

关于linux - Bash - 将函数值设置为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911539/

相关文章:

python - 我无法让 urwid 教程示例正常工作

arrays - bash 中是否有一个 array_combine 函数,我可以在其中从两个函数创建一个关联数组?

linux - 如何检查文件是否是 Bash shell 中的 tar 文件?

linux - 从两端查找具有索引的子字符串

c++ - 可以将 2.1834e+14 转换为实数

python - 我的 Raspbian 无法通过 Python 应用程序重新启动

bash - 如何在 bash 脚本中发出信号?

linux - 拆分字符串(例如使用 bash)但跳过其中的一部分

security - 仅用于代理(ssh-D)访问的登录shell?

shell - 在 ksh 中执行最后一个命令