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

如何用Bash字典实现Bash历史命令计数器?求修正报错代码

修复Bash命令历史使用次数统计脚本

问题说明

我尝试编写一个Bash脚本,用关联数组存储命令(键)和对应的使用次数(值),统计Bash历史中最常用的命令,但当前代码无法正常运行。以下是相关代码和输出示例:

错误的Bash代码

#!/bin/bash
clear

Counter() {
    declare -A dict

    while read line; do
        if [[ -n "${dict[$line]}" ]]; then
            ((${dict[$line]}+1))
        else
            dict["$line"]=1
        fi
    done < /home/$USER/.bash_history

    echo ${!dict[@]} ${dict[@]}
}

Counter

参考Python代码

def Counter(file):
    dict = {}
    for line in file.read().splitlines():
        if line not in dict:
            dict[line] = 1
        else:
            dict[line] += 1

    for k, v in sorted(dict.items(), key=lambda x: x[1]):
        print(f"{k} was used {v} times")

with open("/home/igor/.bash_history") as bash:
    Counter(bash)

参考输出格式

echo $SHELL was used 11 times
sudo apt-get update was used 14 times
ls -l was used 14 times
ldd /opt/pt/bin/PacketTracer7 was used 15 times
zsh was used 17 times
ls was used 26 times

正确的Bash脚本

#!/bin/bash

Counter() {
    declare -A cmd_counts

    # 读取bash历史,跳过空行
    while IFS= read -r line; do
        [[ -z "$line" ]] && continue
        # 计数自增,不存在则自动初始化为0再加1
        ((cmd_counts["$line"]++))
    done < "$HOME/.bash_history"

    # 将关联数组转换为"次数 命令"格式,排序后输出
    for cmd in "${!cmd_counts[@]}"; do
        echo "${cmd_counts[$cmd]} $cmd"
    done | sort -n | awk '{count=$1; $1=""; printf "%s was used %d times\n", substr($0,2), count}'
}

Counter

关键修改说明

  1. 计数逻辑修复:原代码中的((${dict[$line]}+1))仅执行算术运算,未将结果存回数组。改用((cmd_counts["$line"]++)),会自动为不存在的键初始化为0并完成自增,无需额外判断。
  2. 空行处理:增加[[ -z "$line" ]] && continue跳过历史文件中的空行,避免统计无效条目。
  3. 排序与格式化输出:将键值对转换为"次数 命令"的单行格式,用sort -n按数字排序,最后通过awk调整为参考输出的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:48:19