Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting printf'ing an escape sequence contained in a variable

Tags:

bash

Bash code:

yellow="\e[1;33m"
chosen_colour="${yellow}"
declare -i score=300
printf '%s %d\n' "${chosen_colour}" "${score}"

Result:

\e[1;33m 300

Should be:

300 /* in yellow */

How can I interpolate a string value containing an ANSI escape sequence into a printf statement without using either of these syntaxes:

Avoid 1: (works, in fact, but it's wasteful when doing a lot of +=s)

s="${yellow}"
s+="${score}"
s+=...
s+=...
s+=...
s+=...
s+=...
s+=...
s+=...
s+=...

Avoid 2: (hard to do in my case for the sheer number of variables requiring this construct)

printf "${yellow}${score}${a1}${a2}${a3}${a4}${a5}${a6}${a7}${a8}........."

I want to be able to pass the values to be replaced, according to a predefined FORMAT string, using the arguments part of the printf call, as I naively do in the 1st example.

I could live with something like this:

printf \
  '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s...' \
    "${a1}" \
    "${a2}" \
    "${a3}" \
    "${a4}" \
    "${a5}" \
    "${a6}" \
    ...

although ultimately, for my many variables, I would use a construct like this:

${!a*} # or similar
like image 807
Robottinosino Avatar asked Mar 01 '13 01:03

Robottinosino


People also ask

How do I escape a variable in bash?

Escape characters: Bash escape character is defined by non-quoted backslash (\). It preserves the literal value of the character followed by this symbol. Normally, $ symbol is used in bash to represent any defined variable.

How does printf work in bash?

The bash printf command is a tool used for creating formatted output. It is a shell built-in, similar to the printf() function in C/C++, Java, PHP, and other programming languages. The command allows you to print formatted text and variables in standard output.

How do I print a variable in bash?

Moreover, we have also used the printf command to serve the very same purpose. After typing in this program in your Bash file, you need to save it by pressing Ctrl +S and then close it. In this program, the echo command and the printf command is used to print the output on the console.


1 Answers

You do:

printf "^[%s foo" "${a1}" # that is ctrl+v, ESC, followed by %s

or:

printf "\033%s foo" "${a1}"  # 033 octal for ESC
like image 65
perreal Avatar answered Sep 21 '22 22:09

perreal