Shell script function parameter with double quote that ECHO command's SIGN - shell

I'm developing some shell script. please help me
I want to highlight specific strings with FUNCTION like this.
#!/bin/bash
function echoWithColor(){
local InputString=${1}
tput bold;tput setaf 2 # make words color to bright green
echo ${InputString}
tput sgr0 # make words color to default
}
echoWithColor "Hello everyone!"
this works, but I want to add some blank (space text) at end of line like
echo -n "Input your age : "; read AGE
[root#mycomputer scripts]# ./script.sh
Input your age : 9999
but
#!/bin/bash
function echoWithColor(){
local InputString=${1}
tput bold;tput setaf 2 # make words color to bright green
echo ${InputString}
tput sgr0 # make words color to default
}
echoWithColor "-n Input your age : "; read AGE
[root#mycomputer scripts]# ./script.sh
Input your age :9999
Nope
.
#!/bin/bash
function echoWithColor(){
local InputString=${1}
tput bold;tput setaf 2 # make words color to bright green
echo ${InputString}
tput sgr0 # make words color to default
}
echoWithColor "-n \"Input your age : \""; read AGE
[root#mycomputer scripts]# ./script.sh
"Input your age :"9999
Escaping? Nope.
How can I add blank text at end of line?

This happens because you don't quote your variables:
var=" my value "
echo $var without quotes # writes: my value without quotes
echo "$var with quotes" # writes: my value with quotes
Since you want to pass pass multiple strings to echo (both -n and Input your age), you should rewrite the function to take multiple arguments ("$#") instead of just one ($1), and then make sure to quote when using them:
#!/bin/bash
echoWithColor(){
local InputStrings=( "$#" )
tput bold;tput setaf 2 # make words color to bright green
echo "${InputStrings[#]}"
tput sgr0 # make words color to default
}
echoWithColor -n "Input your age: "
Now echoWithColor works exactly like echo, and preserves all spaces you pass to it.

Just add space ' ' in echo ${InputString} command in function just like below
#!/bin/bash
function echoWithColor(){
local InputString=${1}
tput bold;tput setaf 2 # make words color to bright green
echo ${InputString}' '
tput sgr0 # make words color to default
}
echoWithColor "-n Input your age : "; read AGE

Related

Bash and Zsh prompt that ring a bell and do display error code of last command

I want to have the same prompt in both Bash and Zsh. And I want it to:
bell a ring, if the last command failed, and
display its error code.
In Bash, I do have:
BLK="\[$(tput setaf 0; tput bold)\]"
RED="\[$(tput setaf 1; tput bold)\]"
grn="\[$(tput setaf 2)\]"
GRN="\[$(tput setaf 2; tput bold)\]"
yel="\[$(tput setaf 3)\]"
reset_color="\[$(tput sgr0)\]"
PS1='\n\
`if [[ $? -gt 0 ]]; then printf "\[\033[01;31m\]$?"; tput bel; else printf "\[\033[01;32m\]0"; fi`\
\[\033]0;$PWD\007\] \
\[\033[0;32m\]\u#\h\
\[\033[01;30m\]:\
\[\033[;;33m\]\w\
\[\033[36m\]`__git_ps1`\
\[\033[0m\]\n$ '
In Zsh, that's my config:
BLK=$(tput setaf 0; tput bold)
RED=$(tput setaf 1; tput bold)
grn=$(tput setaf 2)
GRN=$(tput setaf 2; tput bold)
yel=$(tput setaf 3)
reset_color=$(tput sgr0)
PROMPT="
%(?.$GRN.$RED)%?$reset_color $grn%n#%m$BLK:$reset_color$yel%~ $reset_color
%(!.#.$) "
And this is how it looks like in the terminal:
Both prompts do ring the bell when there is an error with the last command.
But, in Bash, it prints 0 instead of the right return code of the command that
failed.
How to fix that?
PS- Any better way to improve the above code is welcomed!
The command to test $? itself resets $? to the result of the test. You need to save the value you want to display first.
PS1='\n\
$(st=$?; if [[ $st -gt 0 ]]; then printf "\[\033[01;31m\]$st"; tput bel; else printf "\[\033[01;32m\]0"; fi)\
\[\033]0;$PWD\007\] \
\[\033[0;32m\]\u#\h\
\[\033[01;30m\]:\
\[\033[;;33m\]\w\
\[\033[36m\]`__git_ps1`\
\[\033[0m\]\n$ '
I would recommend building up the value of PS1 using PROMPT_COMMAND, instead of embedding executable code. This gives you more flexibility
for commenting and separating any computations you need from the actual
formatting. make_prompt doesn't need quite so many lines, but it's
just a demonstration.
set_title () {
printf '\033]0;%s%s' "$1" "$(tput bel)"
}
make_prompt () {
local st=$?
local c bell
bell=$(tput bel)
# Green for success, red and a bell for failure
if [[ $st -gt 0 ]]; then
c=31
else
c=32 bell=
fi
win_title=$(set_title "$PWD")
git_status=$(__git_ps1)
PS1="\n"
PS1+="\[\e[01;${c}m$bell\]" # exit status color and bell
PS1+=$st
PS1+="\[$win_title\]" # Set the title of the window
PS1+="\[\e[0;32m\]" # Color for user and host
PS1+="\u#\h"
PS1+="\[\e[01;30m\]" # Color for : separator
PS1+=":"
PS1+="\[\e[;;33m\]" # Color for directory
PS1+="\w"
PS1+="\[\e[36m\]" # Color for git branch
PS1+=$git_status
PS1+="\[\e[0m\]" # Reset to terminal defaults
PS1+="\n$ "
}
PROMPT_COMMAND=make_prompt
zsh already has terminal-agnostic escape sequences for adding color.
PROMPT="%B%(?.%F{green}.%F{red}$(tput bel))%?%f%b %F{green}%n#%m%F{black}%B:%b%F{yellow}%~ %f%(!.#.$) "
Any external command (such as printf or tput) resets the value of $?. You need to capture it in a variable before that happens.
rc=$?
if [ $rc -gt 0 ]; then
printf "\[\033[01;31m\]$rc"
tput bel
else
printf "\[\033[01;32m\]0"
fi
(Unwrapped for legibility; this will replace the code inside the backticks.)
Notice that this will still overwrite the value of $?; perhaps add exit $? at the end to properly preserve the value.

Efficiently reusing color codes in a printf %s substitution in bash

biwhite=$(tput bold)$(tput setaf 7)
color_off=$(tput sgr0)
printf "%s$USER%s at %s$HOME%s has path %s$PATH%s" "$biwhite" "$color_off" "$biwhite" "$color_off" "$biwhite" "$color_off"
Is there a printf shortcut to avoid having to define every %s when I want to add color to only certain parts of a statement?
Entering "$biwhite" "$color_off" 3 times seems redundant.
It's good practice to avoid putting parameter expansions in the format string of printf, in case they contain percent signs as well. That said, parameter substitution offers a way around some of the repetitiveness.
w="${biwhite}X${color_off}"
printf "%s at %s has path %s" "${w/X/$USER}" "${w/X/$HOME}" "${w/X/$PATH}"
It's not foolproof, but it's fairly unlikely that X will appear in the output of tput. You can pick a longer string instead, at the cost of more typing.
I'm afraid, though, that adding color codes to a string is inherently painful.
I think you could write a bash function:
biwhite=$(tput bold)$(tput setaf 7)
color_off=$(tput sgr0)
whiten() {
echo "$biwhite$1$color_off"
}
echo "$(whiten "$USER") at $(whiten "$HOME") has path $(whiten "$PATH")"
Also, why use printf if you're not using any of it's formatting capabilities?
Provided below is a function which colorizes every other argument, starting with the second. (Thus, a non-colorized prefix can be provided by passing a non-empty string in this first position, or a colorized one by leaving it empty, as here).
Notably, no subshells are involved in this code's execution except in the tput invocations used for demonstrative purposes. It is thus, while verbose, very low-overhead to execute.
biwhite=$(tput bold)$(tput setaf 7)
color_off=$(tput sgr0)
# colorize every other argument, starting from the 2nd.
colorize_words() {
local start_color end_color
: "${start_color:=$biwhite}" "${end_color:=$color_off}"
while (( $# )); do
printf '%s' "$1"
shift || break
printf '%s%s%s' "$start_color" "$1" "$end_color"
shift || break
done
printf '\n'
}
colorize_words "" "$USER" " at " "$HOME" " has path " "$PATH"
This can be customized by passing start_color and end_color values to an individual invocation; for example:
# this prints every other argument in red
start_color=$(tput setaf 1) colorize_words "hello " "cruel " world

Why isn't bash accepting my color coding?

I've got a simple code setup, but for whatever reason it refuses to operate how it should
#!/bin/bash
RED='\033[0:31m'
RESET='\033[0m'
Basically these are some simple color encodings
Next thing I have is
for file in ./dir/*.c; do
echo "File [${RED}$file${RESET}] has been launched"
My expected result would be
File [myprogram.c] has been launched (while the name would be in red color)
Instead it just refuses to encode the color and dumps
File [\033[0:31m] has been launched
Any idea what I'm doing wrong?
First because red is '\033[31m'. What you wrote means something else, read below.
Then, because the codes need to be interpreted.
This won't work:
$ red='\033[31m'
$ echo "${red}Hello"
But this would:
$ red='\033[31m'
$ echo -e "${red}Hello"
Or, you can assign the interpreted values to a variable:
$ red="$(echo -e '\033[31m')"
$ red="$(printf '\033[31m')"
Then the escapes don't need to be interpreted:
$ echo "${red}Hello"
What you wrote (besides using a colon where a semicolon should be) was setting the "boldness" of the foreground, or 0 for thin/light and 1 for bold/bright.
$ printf '\033[31mHello\033[0;31mHello\033[1;31mHello'
Also, 3x is for foreground 4x is for background:
$ printf '\033[31;42mHello\033[0;44;31mHello\033[1;43;31mHello\033[0m'
A full table could be printed with this:
$ printf "$(printf '%s' 033[{0,1}';'3{1..8}{';'4{1..8}mXXX,';'40m=OoO\\033[0m\\n} )"
With tput
#!/bin/bash
red=$(tput setaf 1)
reset=$(tput sgr0)
for file in ./dir/*.c; do
echo "File [${red}$file${reset}] has been launched"
done
with printf
#!/bin/bash
RED='\033[0;31m'
RESET='\033[0m'
for file in ./dir/*.c; do
printf "File [${RED}$file${RESET}] has been launched"
done
There is a typo in your code. Red color code is [031m. The ASCII codes always start with an escape character, octal 33: \033. Thus, to start printing red text join the two sequences: \033[031m.
I find this post very helpful. In particular, the author recommends to use tput instead of the hard-coded values, and I agree with him.
Example
die() {
local message="$1"
: ${message:=Aborted}
# See info bash BASH_SOURCE, info bash FUNCNAME, info bash BASH_LINENO
printf '%s at %s:%s line %d\n' \
"$message" ${BASH_SOURCE[1]} ${FUNCNAME[1]} ${BASH_LINENO[0]} >&2
exit 1
}
# See man 1 tput, man 5 terminfo.
red=$(tput setaf 1) || die
noattr=$(tput sgr0) || die
# If tput is unavailable (very unlikely), use the hardcoded values as follows.
# The ANSI codes always start with the escape character (octal 33).
#esc='\033'
#red="${esc}[031m"
#noattr="${esc}[0m"
# %b causes printf to expand backslash escape sequences. See info bash printf.
printf '%b%s%b\n%s\n' "$red" 'red text' "$noattr" 'normal text'
Note the use of printf. Don't use echo in new software.

Bash colour one word using echo

I am wanting to colourize one word in the middle of an echo sentence, but can't seem to achieve this.
This works:
#!/bin/bash
wipe="\033[1m\033[0m"
yellow='\E[1;33'
echo -e "$yellow"
echo Hello World
echo -e "$wipe"
But this doesn't:
#!/bin/bash
wipe="\033[1m\033[0m"
yellow='\E[1;33'
black="40m"
echo -e "Output a $yellow coloured $wipe word."
# or
echo -e "Output a ${yellow} coloured ${wipe} word."
What am I stupidly doing wrong? :)
Much better, use tput to set a foreground colour:
textreset=$(tput sgr0) # reset the foreground colour
red=$(tput setaf 1)
yellow=$(tput setaf 2)
echo "Output a ${yellow} coloured ${textreset} ${red} word ${textreset}."
You forgot an m in your ANSI escape code for yellow. This works:
yellow='\E[1;33m'

Bash script to print a text file in color

I have a text file with three paragraphs. I want to display the different paragraphs in different colors using bash script commands. Paragraph 1 in red, paragraph 2 in blue and paragraph 3 in cyan.
I managed to display lines in color using commands like
echo -e '\E[32;47m Green.'; tput sgr0
However, I want to parse my file and change colors when there is a new paragraph. I would appreciate for some hints.
The input /tmp/FILE : http://pastie.org/4928415
The script :
#!/bin/bash
c=1
tput setaf $c
while read a; do
[[ $a =~ ^$ ]] && tput setaf $((++c))
echo "$a"
done < /tmp/FILE
tput sgr0
The output :
Here's an awk solution, which uses in turn elements of an array of color settings:
BEGIN { nc = split("\33[31;47m \33[34;43m \33[36;40m", colors, " ");
c=1; print colors[c] }
{ print }
/^$/ { c = 1+(c%nc); print colors[c]}
[Edit: The above erroneously adds an extra blank line between paragraphs. Corrected code is as follows:
BEGIN { nc = split("\33[31;47m \33[34;43m \33[36;40m", colors, " ");
c=1; printf "%s", colors[c] }
/^$/ { c = 1+(c%nc); print colors[c]}
!/^$/
The !/^$/ causes any non-blank line to print as is. (End Edit)].
If the above is in file 3-para.awk and data is in file 3-para.data, use a command like awk -f 3-para.awk 3-para.data to get output like the following.
For more convenient use, define a function that invokes the script and then resets colors to default:
tricolor() {
awk -f 3-para.awk $1; tput sgr0
}
Use the function via (eg) tricolor 3-para.data

Resources