0

I am display the 256 colors for tput by colouring tho background colour using the following bash function.

 tput-bgcolours ()
 {
    for color in {0..255}; do
        bg=$(tput setab $color)
        echo -n $bg" "
    done
    echo $(tput sgr0)
 }

How can I pass a range of values to the function rather that looking all colours from 0 to 255?

3
  • Your original version made more sense than this one. Jun 28 '21 at 1:40
  • Have had a go at passing parameters with defaults.
    – Pietru
    Jun 28 '21 at 1:43
  • Take colors256() in mywiki.wooledge.org/BashFAQ/037 do sed -i s/setaf/setab/g and try it. It includes nice ways to select panels of colors.
    – A.B
    Jun 28 '21 at 14:51
1

You can do:

tput-bgcolours()
{
    for color in "$@"; do
        tput setab $color
        printf " "
    done
    tput sgr0
}

tput-bgcolours {0..10} {30..40}

The "$@" is the set of arguments to the function. Now, the caller of the function can pass the values that they're interested in printing.

This also has the benefit that you don't have to use a range:

tput-bgcolours 1 7 15 8 1
1
  • @Pietru Note that there's no need to force the colors to be sequential. Jun 28 '21 at 1:57
1

A couple of alternatives:

  • printf is in general preferred over echo.
  • One do not need to echo tput

sh compatible

tput-bgcolours() {
    for color in $(seq "$1" "$2"); do
        tput setab "$color"
        printf ' '
    done
    tput sgr0
}

bash loop

tput-bgcolours() {
    for (( c = $1; c <= $2; ++c )); do
        tput setab "$c"
        printf ' '
    done
    tput sgr0
}

Usage:

tput-bgcolours FROM TO

I.e.

tput-bgcolours 0 16

You could of course also add a test in the functions like (test if length of arg is empty):

if [ -z "$1" ] || [ -z "$2" ]; then
    return 1
fi

or use defaults:

from=${1:-0}
to=${2:-255}
6
  • does (( color = $1; color <= $2; color++ )) not work in bash?
    – Pietru
    Jun 28 '21 at 1:47
  • It is actually #!/bin/bash
    – Pietru
    Jun 28 '21 at 1:52
  • I get "bash: ((: color <= : syntax error: operand expected (error token is "<= ")"
    – Pietru
    Jun 28 '21 at 1:55
  • GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
    – Pietru
    Jun 28 '21 at 1:56
  • Do I need #!/bin/bash in my .bashrc ?
    – Pietru
    Jun 28 '21 at 1:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.