为什么我的 Bash 变量设置较晚,动画文本功能

问题描述 投票:0回答:1

我正在编写一个 Bash 函数,该函数仅在我第二次调用它时才起作用。它应该做的是使用缓动函数编写一个字符串,以便快速显示字符串的第一部分,然后减慢速度以完成字符串的最后一个单词。需要注意的是,它应该使用 tput 定义的标准终端颜色来显示颜色。

第二次运行时效果很好。第一次运行时,它在终端中显示转义序列,而不是我要求的颜色。

这是我的代码:

#!/usr/bin/env bash

# Easing function: ease_in_expo
ease_in_expo() {
    local t=$1
    echo "scale=4; if ($t == 0) 0 else 1 * e(10 * ($t - 1))" | bc -l
}

animate_text_with_ease_in_expo() {
    text="$1"
    delay="$2"

    # Regular Colors
    RESET=$(tput sgr0)         # Text Reset
    BLACK=$(tput setaf 0)      # Black
    RED=$(tput setaf 1)        # Red
    GREEN=$(tput setaf 2)      # Green
    YELLOW=$(tput setaf 3)     # Yellow
    BLUE=$(tput setaf 4)       # Blue
    PURPLE=$(tput setaf 5)     # Purple
    CYAN=$(tput setaf 6)       # Cyan
    WHITE=$(tput setaf 7)      # White

    for ((i = 0; i < ${#text}; i++)); do
        progress=$(ease_in_expo "$((i + 1)) / ${#text}")
        sleep "$(echo "$delay * $progress" | bc -l)"

        # Write the string to output
        echo -n "${text:$i:1}"
    done
}

animate_text_with_ease_in_expo "Tutti ${RED}frutti${RESET}, oh ${CYAN}rooty${RESET}; A wop bop b-luma b-lop bam ${GREEN}boom." 0.30

Bash 专家能否指出我在第一次运行函数时加载这些颜色变量的正确路径?

尝试将颜色变量定义为 ANSI 转义序列以及 tput setaf。尝试将颜色定义放在单独的函数中,首先调用该函数,然后回调到我的 animate_text_with_ease_in_expo 函数。尝试在声明颜色定义后通过 text=$text 重新加载“text”变量。

第一次运行的输出:

Tutti \033[0;31mfrutti, oh \033[0;36mrooty; A wop bop b-luma b-lop bam boom.

第二次运行的输出:

Tutti frutti, oh rooty; A wop bop b-luma b-lop bam boom.

(以上,加上适当的颜色)

上面的代码全部写入一个名为“string-problem.sh”的Bash脚本中。进入脚本所在的目录后,我通过以下方式调用它:

. string-problem.sh
bash variables colors ansi-escape tput
1个回答
0
投票

简而言之:

func() {
  hello=world
}
func "${hello}"

hello
正在函数内部设置。在
"${hello}"
变量
hello
时未设置,因此它扩展为空。

只需设置变量一次。

# Regular Colors
RESET=$(tput sgr0)         # Text Reset
BLACK=$(tput setaf 0)      # Black
RED=$(tput setaf 1)        # Red
GREEN=$(tput setaf 2)      # Green
YELLOW=$(tput setaf 3)     # Yellow
BLUE=$(tput setaf 4)       # Blue
PURPLE=$(tput setaf 5)     # Purple
CYAN=$(tput setaf 6)       # Cyan
WHITE=$(tput setaf 7)      # White

animate_text_with_ease_in_expo() {
    text="$1"
    delay="$2"
    ...
}

animate_text_with_ease_in_expo "Tutti ${RED}frutti${RESET}, oh ${CYAN}rooty${RESET}; A wop bop b-luma b-lop bam ${GREEN}boom." 0.30
© www.soinside.com 2019 - 2024. All rights reserved.