【问题标题】:Getting value from function, use that value to get colored output in shell从函数中获取值,使用该值在 shell 中获取彩色输出
【发布时间】:2015-07-08 09:05:41
【问题描述】:

(使用 zsh)我只是想在终端中打开一个新选项卡时获得随机颜色输出。为了实现这一点,我编写了以下 shell 脚本,但它没有按预期工作:

#Standard Colors
red='\033[0;31m'
NC='\033[0m' # No Color
black='\033[0;30m'
blue='\033[0;34m'
green='\033[0;32m'
cyan='\033[0;36m'
purple='\033[0;35m'
yellow='\033[1;33m'
lgreen='\033[1;32m'
lblue='\033[1;34m'
lred='\033[1;31m'
lcyan='\033[1;36m'
#Array color
colr=(red blue green cyan purple yellow lgreen lblue lred lcyan)

#Get random number for colors
randcolr()
{
  sz=${#colr[@]}
  randval=$(( ( RANDOM % sz )  + 1 ))
  echo "${colr[randval]}"
}

echo -e "$(randcolr)TESTING"

它没有得到彩色输出,而是写了颜色的名称和“TESTING”,例如lgreenTESTING。有什么帮助吗?(我正在使用 zsh)

函数randcolr 在终端内总是给出相同的值。

【问题讨论】:

  • 你在randcolr()里面用什么sz?好的,现在你编辑了你的代码,我看到了。

标签: shell sh zsh zshrc oh-my-zsh


【解决方案1】:

当你定义你的数组时,你使用的是字符串而不是变量:

colr=(red blue green cyan purple yellow lgreen lblue lred lcyan)

应该是:

colr=($red $blue $green $cyan $purple $yellow $lgreen $lblue $lred $lcyan)

【讨论】:

  • 或者,使用${(P)$(randcolr)} 扩展由randcolr 的输出命名的变量。
猜你喜欢
  • 2020-03-30
  • 2016-04-10
  • 2011-10-10
  • 1970-01-01
  • 2012-06-26
  • 2019-02-23
  • 2012-04-21
  • 2014-01-08
  • 2017-02-09
相关资源
最近更新 更多