Home > Back-end >  How to assign a color to a variable within a bash function
How to assign a color to a variable within a bash function

Time:02-03

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 s\n" "$target_host"  "${RED}${SMB}${NC}"
   else
     printf "%-35s s\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.

CodePudding user response:

This should achieve what you expected :

NC=$'\033[0m'
RED=$'\033[0;31m'
  •  Tags:  
  • Related