1

Shell显示彩色文字

 2 years ago
source link: https://mryqu.github.io/post/shell%E6%98%BE%E7%A4%BA%E5%BD%A9%E8%89%B2%E6%96%87%E5%AD%97/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Shell显示彩色文字

时间:

2020-11-26

  |   分类: Tool   Linux  

  |  

阅读: 189 字 ~1分钟

昨天学习一下如何使用shell在屏幕显示彩色文字。解决方案有两种:1. 转义字符 2. tput设置文本颜色。
在Linux上这两种方式都正常工作,在FreeBSD上第二种方式不起作用。
代码如下:

#!/bin/ksh

println() {
  printf "%s\n" $*
}

##########################
# Solution 1
##########################

colorsEnabled() {
  if [ $TERM == 'TERM' ]
  then
    return 0
  fi
  return 1
}

printlnColor() {
  c=$1
  shift
  msg=$*;
  colorsEnabled
  if [ $? == 1 ]
  then
    printf "\033[0;%dm%s\033[0m\n" $c "$msg"
  else
    printf "%s\n" "$msg"
  fi
}

# Success
printlnSuccess() {
  printlnColor 32 $*
}

# Warning
printlnWarning() {
  printlnColor 33 $*
}

# Failure
printlnFailure() {
  printlnColor 31 $*
}

# Verbose
printlnVerbose() {
  printlnColor 35 $*
}

# Emphasis
printlnEmphasis() {
  printlnColor 36 $*
}

# Note
printlnNote() {
  printlnColor 37 $*
}

##########################
# Solution 2
##########################

println_color() {
  c=$1
  shift
  msg=$*;
  tput setaf $c
  printf "%s\n" "$msg"
  tput sgr0
}

# Success
println_success() {
  println_color 2 $*
}

# Warning
println_warning() {
  println_color 3 $*
}

# Failure
println_failure() {
  println_color 1 $*
}

# Verbose
println_verbose() {
  println_color 5 $*
}

# Emphasis
println_emphasis() {
  println_color 6 $*
}

# Note
println_note() {
  println_color 7 $*
}


printlnEmphasis hahaha 123
echo "====================="
println_emphasis hahaha 123

标题:Shell显示彩色文字
作者:mryqu
声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK