Assessing the color of formatted command output

I use diff to format a string that includes tput color variables, and I cannot evaluate these variables without using the "evil" eval command.

The command that creates the line:

output1="$(diff --changed-group-format="\${RED}%=\${CLS}" <(echo -e "${nstr1}") <(echo -e "${nstr2}")|tr -d '\n')"

and outputs this:

[String n${RED}â${CLS}m${RED}è™${CLS}]

I looked and looked for other answers, but nothing works except:

eval echo "${output1}"

From what I read, my 3 options are: eval(bad), indirect extension (better) and arrays (best). Each indirect failure attempt failed. I would like to use an array parameter, but I just don't see how it will be applied here. Did I miss something?

I don't think this is relevant, but variables and plotting strings sent to diff are in another question here .

+4
1

Bash, , :

#!/usr/bin/env bash

# Define the variables containing ANSI color sequences.
RED="$(tput setaf 1)"
CYA="$(tput setaf 6)"
CLS="$(tput sgr0)"

# Sample input string
str='[String n${RED}â${CLS}m${CYA}è™${CLS}]'

# Replace the placeholders with their corresponding variable values.
str=${str//'${RED}'/${RED}}
str=${str//'${CYA}'/${CYA}}
str=${str//'${CLS}'/${CLS}}

# Output the result.
echo "$str"

, , Bash, , :

  • ${<varName>//<search>/<replace>} <search> <replace> <varName>.
  • '${RED}', , - , , .
  • ${RED}, , - , , ${RED} ${RED}.

:

printColored() {
  local str=$1
  local RED="$(tput setaf 1)" CYA="$(tput setaf 6)" CLS="$(tput sgr0)"
  str=${str//'${RED}'/${RED}}
  str=${str//'${CYA}'/${CYA}}
  str=${str//'${CLS}'/${CLS}}
  printf '%s\n' "$str"
}

printColored '[String n${RED}${CLS}m${CYA}è™${CLS}]'

, ${CLS} ${RST} ( "reset" ) - , "cls" .

+1

Source: https://habr.com/ru/post/1621030/


All Articles