Bash script: problem with a function which use colors

Hello guys :slight_smile:

I've a some issue with a function which use the bash colors in my script.
An example :

#!/bin/bash

set -x

log_in(){    
    host="srv1"
    remote_files="log/"
    LOG_FILE="logfile"

    green='\033[0;32m'
    red='\033[0;31m'
    none='\033[0m'

    if [[ $1 = "red" ]]; then
    color_in_red=("${red}"$2"${none}")
        echo -e "$color_in_red"
        echo -e "$(date)" "$2" >> "${LOG_FILE}"
    elif [[ $1 = "green" ]]; then
    color_in_green=("${green}"$2"${none}")
        echo -e "$(date)" "$2" >> "${LOG_FILE}"
        echo -e "$color_in_green"
fi
}
log_in red ""$host" The read right is missing on \""$remote_files"\""

The problem is it write good in the logfile but in output it stop write from the first variable, I should be more clear with the output that I had :

rsync_user@vmtest1:/home/scripts/test$ ./test.sh
+ host=srv1
+ remote_files=log/
+ LOG_FILE=logfile
+ log_in green 'srv1 The read right is missing on "log/"'
+ green='\033[0;32m'
+ red='\033[0;31m'
+ none='\033[0m'
+ [[ green = \r\e\d ]]
+ [[ green = \g\r\e\e\n ]]
+ color_in_green=("${green}"$2"${none}")
++ date
+ echo -e 'Wed Jan 18 17:33:16 CET 2017' 'srv1 The read right is missing on "log/"'
+ echo -e '\033[0;32msrv1'
srv1
rsync_user@vmtest1:/home/scripts/test$

And in the logfile, it works :

rsync_user@vmtest1:/home/scripts/test$ cat logfile
Wed Jan 18 17:33:16 CET 2017 srv1 The read right is missing on "log/"

Then, all in my console become red or green.. until I type "ll" maybe another commands..

If someone can help me, I would appreciate. :b:

I think that color_in_red=("${red}"$2"${none}") this is incorrect, putting it in ( ) like that will make it an array. You should just do color_in_red="${red}$2${none}"

Also, if you're using BASH, you can avoid a lot of those echo -e 's by just storing the binary values in the first place.

Also, you don't have to re-open the same logfile every time to print one line, you can open the logfile once and write to it as many times as you want:

Also, if you print the color ones to stderr, they will go straight to console and won't muck up your pipes, etc.

#!/bin/bash

exec 5>>logfile


logthis() {
    green=$'\033[0;32m' # The variables will hold actual escape sequence, not backslash-zero-three-three
    red=$'\033[0;31m'
    none=$'\033[0m'

    printf "%s: %s\n" "$(date)" "$1" >&5 # Print to file opened above into FD 5
    printf "%s%s%s\n" "$green" "$1" "$none" >&2 # To stderr
}

1 Like

It work perfectly ! thanks

1 Like