help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Construct ANSI colour codes


From: pauline-galea
Subject: Re: Construct ANSI colour codes
Date: Wed, 7 Apr 2021 23:39:47 +0200

> Sent: Thursday, April 08, 2021 at 9:03 AM
> From: "Greg Wooledge" <greg@wooledge.org>
> To: help-bash@gnu.org
> Subject: Re: Construct ANSI colour codes
>
> Why are you making this so hard?
>
> declare -A color=(
>   [black]="$(tput setaf 0)"
>   [red]="$(tput setaf 1)"
>   [green]="$(tput setaf 2)"
>   [yellow]="$(tput setaf 3)"
>   [blue]="$(tput setaf 4)"
>   [magenta]="$(tput setaf 5)"
>   [cyan]="$(tput setaf 6)"
>   [white]="$(tput setaf 7)"
> )
> sgr0="$(tput sgr0)"
>
> echo "${color[green]}hello${sgr0} ${color[red]}world${sgr0}"
> printf 'Price: %s$%.2f%s\n' "${color[blue]}" "$price" "$sgr0"
>
> Or you can use scalar variables like "red" "blue" and so on, instead of
> the associative array.
>
> I gave two different examples for output.  You can use either, or both,
> or come up with your own.
>
> If you insist on initializing the color variables inside a function,
> and if you go with the array, then you might want to add the -g option
> to make it global.

The reason I thought about using a function is because I would need
to apply the colour scheme for many bash scripts.  I can just call the
function to activate the colouring.  And if you want the hardwired codes,
you simply call a different function.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]