bashshellcolors

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


I have following script where i want to to print the command Variable SMB into the RED colour within a function but that's not working.

Below is the Script:

Script:

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

NC='\033[0m'
RED='\033[0;31m'

remote_connect() {
   target_host=$1
   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 "$@"' --

Result:

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

If i use echo like below it works, but then the lifet and right justify as i am trying with print that's not possible with echo.

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

Expected:

Second column that is Samba version 4.9.1 should be printed in Red color.


Solution

  • This should achieve what you expected:

    NC=$'\033[0m'
    RED=$'\033[0;31m'
    

    The dollar sign followed by single quoted string is ANSI-C quoting. From the page in the bash manual

    Character sequences of the form $'string' are treated as a special kind of single quotes. The sequence expands to string, with backslash-escaped characters in string replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded [...]

    In short, strings in bash behave differently from most languages. In this particular instance, the behavior difference is that bash doesn't decode escape sequences by default.