【问题标题】:What happens in detail in this bash script?在这个 bash 脚本中详细发生了什么?
【发布时间】:2021-02-16 16:17:56
【问题描述】:

根据学习一些关于 bash 脚本的知识,我发现了这个有趣的 bash 脚本。

我很好奇它的详细工作原理,但我是 bash 脚本的初学者。

我了解,分号分隔多个命令,并且使用了一些预定义的变量,例如 $LINES$RANDOM,稍后会通过管道传输某些内容,但仅此而已。

为什么只有在一行中粘贴才能执行?

信息: 我在 Windows 10 上使用 Git Bash

也许有经验的人可以走一遍?需要额外的解释。

echo -e "\e[1;40m" ; clear ; while :; do echo $LINES $COLUMNS $(( $RANDOM % $COLUMNS)) $(( $RANDOM % 72 )) ;sleep 0.05; done|awk '{ letters="ABCDEFGHIJKLMNOPQRSTUVWXYZムキノフレアイ√メリ0123456789()₿₹₵иηøρгţчςợгµαϤδχϞϗγπϥ";c=$4; letter=substr(letters,c,1);a[$3]=0;for (x in a) {o=a[x];a[x]=a[x]+1; printf "\033[%s;%sH\033[2;32m%s",o,x,letter; printf "\033[%s;%sH\033[1;37m%s\033[0;0H",a[x],x,letter;if (a[x] >= $1) { a[x]=0; } }}'

【问题讨论】:

    标签: bash shell echo git-bash


    【解决方案1】:

    非常有趣的脚本。为了清楚起见,让我分解一下单行,添加一些 cmet,并稍作修改:

    #!/bin/bash
    
    shopt -s checkwinsize                   # bash updates the values of LINES and COLUMNS
    echo -e "\e[1;40m"
    clear
    while :; do
        echo "$LINES" "$COLUMNS" "$(( $RANDOM % $COLUMNS))" "$(( $RANDOM % 72 ))"
        sleep 0.05
    done | awk '
        {letters="ABCDEFGHIJKLMNOPQRSTUVWXYZムキノフレアイ√メリ0123456789()₿₹₵иηøρгţчςợгµαϤδχϞϗγπϥ"
        c=$4
        letter=substr(letters, c, 1)        # pick a character from letters in random
        a[$3]=0                             # a[x] holds a row position of column x
                                            # pick a column in random to put a new character
        for (x in a) {                      # loop over the columns which has characters on it
            o=a[x]                          # original row position of column x
            a[x]=a[x]+1                     # increment the row position of column x
                                            # to express the character falls down
            printf "\033[%s;%sH\033[2;32m%s", o, x, letter
            printf "\033[%s;%sH\033[1;37m%s\033[0;0H", a[x], x, letter
            if (a[x] >= $1) {               # if the row position of column x reaches the bottom line
                a[x]=0                      # then reset the row position
            }
        }
    }'
    

    转义序列,动画的重点,需要额外解释:

    echo -e "\e[1;40m"              set the character bold, and the background black
    
    printf "\033[%s;%sH", o, x      move cursor to row "o", column "x"
    printf "\033[2;32m%s", letter   put "letter" with dim green color
    
    printf "\033[%s;%sH", a[x], x   move cursor down to row "a[x]", column "x"
    printf "\033[1;37m%s", letter   put "letter" with white color
    printf "\033[0;0H"              move cursor to the top-left corner
    

    【讨论】:

    • 也许还要注意,tput 通常比对特定终端的硬编码控制序列更好。
    • @tripleee 感谢您的有用评论。我同意这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多