You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DevOps学习:按内存/CPU排序进程的Bash脚本语法错误求助

Bash脚本报错排查与修复方案

语法错误核心排查点

  • if判断的空格规则不符合要求:Bash语法明确要求if关键字和左中括号[之间必须留空格,左中括号[和判断条件、判断条件和右中括号]之间也必须留空格,原代码里if[$sorting = 1];完全未符合空格要求,是触发语法报错的最主要原因。
  • 缺少then关键字:Bash的if分支结构固定格式为if [ 条件 ]; then 执行逻辑; else 执行逻辑; fi,原代码的if条件后没有写then,会直接抛出语法错误。
  • ps命令参数拼接错误:原代码里ps auck-%mem属于参数格式错误,ps aux是查询所有进程的标准参数,按资源倒序排序需要单独加--sort=-%mem(内存倒序)或--sort=-%cpu(CPU倒序)参数,参数之间需要用空格分隔。

功能优化建议

  • 避免硬编码用户名:原代码用grep kami过滤当前用户进程,可替换为grep $USER自动获取当前执行脚本的用户,适配不同运行环境。
  • 增加输入合法性校验:可对用户输入的排序选项、输出行数做范围校验,避免输入非法值导致脚本运行异常。

修复后完整脚本

#!/bin/bash

# 读取用户输入的排序规则
read -p "Press 1 to sort by memory OR 2 to sort by CPU consumption: " sorting
# 读取用户输入的输出行数
read -p "How much output should be displayed, choose a number between 1-9: " output

# 输入合法性校验
if ! [[ "$sorting" =~ ^[12]$ ]] || ! [[ "$output" =~ ^[1-9]$ ]]; then
    echo "Input error: sort option must be 1 or 2, line count must be 1-9"
    exit 1
fi

# 按用户选择排序输出进程
if [ "$sorting" = 1 ]; then
    ps aux --sort=-%mem | grep "$USER" | head -n "$output"
else
    ps aux --sort=-%cpu | grep "$USER" | head -n "$output"
fi

内容的提问来源于stack exchange,提问作者Kami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:45:07