如何为 bash 函数中的变量分配颜色

How to assign a color to a variable within a bash function

我有以下脚本,我想在 函数中将命令变量 SMB 打印成红色,但这不起作用。

脚本如下:

脚本:

#!/bin/bash
read -rsp $'Please Enter password below: ' SSHPASS
echo -n  ""
export SSHPASS

NC='3[0m'
RED='3[0;31m'

remote_connect() {
   target_host=
   sshpass -e ssh -q "${target_host}"  "true" -o StrictHostKeyChecking=no -o ConnectTimeout=60 2>>/dev/null
   if [[ $? -eq 0 ]]
   then
     SMB=$(sshpass -e ssh -q -t "$target_host" "sudo smbstatus |grep ^Samba")
     printf "%-35s %15s\n" "$target_host"  "${RED}${SMB}${NC}"
   else
     printf "%-35s %15s\n" "$target_host" "Unable to get the ssh connection"
fi
}  2>/dev/null
export -f remote_connect
< host_list xargs -P5 -n1 -d'\n' bash -c 'remote_connect "$@"' --

结果:

tdi1990.colx.fox.com       3[0;31m Samba version 4.9.1 3[0m \n
tdi1856.colx.fox.com       3[0;31m Samba version 4.9.1 3[0m \n
tdi1993.colx.fox.com       3[0;31m Samba version 4.9.1 3[0m \n

如果我像下面那样使用 echo 它会起作用,但是当我尝试使用 echo 打印时,lifet 和 right justify 是不可能的。

echo -e  "$target_host"  "${RED}${SMB}${NC}"

预期:

第二列 Samba version 4.9.1 应该用红色打印。

这应该达到您的预期:

NC=$'3[0m'
RED=$'3[0;31m'