bash - 如何将shell脚本变量从字符串转换为整数

标签 bash shell ubuntu

我的脚本有一行测量正在运行的进程的实例数
procs=$(pgrep -f luminati | wc -l);
然而,即使 $procs 的内容是一个数字,shell 脚本不存储 $procs作为整数。它被存储为一个字符串。

因此我不能运行条件
if $procs > 3
有没有办法将此变量转换为整数类型?

最佳答案

在 bash >truncate写入文件。您可能有一个名为 3 的文件现在。您应该使用比较器 -gt :

if [[ "$procs" -gt 3 ]]; then
    ...
fi

此外,整数和字符串没有单独的类型。

编辑:
正如@chepner 解释的那样,为了与 POSIX 兼容,您应该使用单括号:
if [ "$procs" -gt 3 ];

关于bash - 如何将shell脚本变量从字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49614730/

相关文章:

php - Git::Windows:从远程存储库中提取区分大小写的文件

bash - 编写没有 shebang 行的 Bash 脚本

shell - 使用 Django shell 实例化具有外键属性的对象

Ubuntu Upstart 不会重生

python - 确定 python 是否正在 Ubuntu Linux 中运行

bash - 读取 : Illegal option -s in shell scripting

python - 如何从 Flask 应用程序执行 Shell 脚本

python - check_output 的参数太长?失败并出现错误 127

java - 调用 Runtime.exec 时捕获标准输出

python - 类型错误 : __init__() takes exactly 1 argument (2 given)