我是用下面的bash函数显示彩色背景颜色的256种颜色。
tput-bgcolours ()
{
for color in {0..255}; do
bg=$(tput setab $color)
echo -n $bg" "
done
echo $(tput sgr0)
}如何将范围的值传递给函数,而不是将所有颜色从0传递到255?
发布于 2021-06-28 01:43:59
你可以:
tput-bgcolours()
{
for color in "$@"; do
tput setab $color
printf " "
done
tput sgr0
}
tput-bgcolours {0..10} {30..40}"$@"是函数的一组参数。现在,函数的调用方可以传递他们感兴趣的值。
这也有一个好处,您不必使用范围:
tput-bgcolours 1 7 15 8 1发布于 2021-06-28 01:45:46
有几个备选方案:
printf是总体而言优先于echo的首选。echo tputsh兼容
tput-bgcolours() {
for color in $(seq "$1" "$2"); do
tput setab "$color"
printf ' '
done
tput sgr0
}bash循环
tput-bgcolours() {
for (( c = $1; c <= $2; ++c )); do
tput setab "$c"
printf ' '
done
tput sgr0
}用法:
tput-bgcolours FROM TO也就是说。
tput-bgcolours 0 16当然,您也可以在(test if length of arg is empty)这样的函数中添加一个测试:
if [ -z "$1" ] || [ -z "$2" ]; then
return 1
fi或者使用默认值:
from=${1:-0}
to=${2:-255}https://unix.stackexchange.com/questions/656083
复制相似问题