printf 在标准输出中插入随机空格

printf inserts random spaces in stdout

我有一个 bash 脚本,它使用 printf 来打印一些彩色的 STDOUT。我注意到有时它会插入空格:

#!/usr/bin/env bash

### define colors
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
LIME_YELLOW=$(tput setaf 190)
POWDER_BLUE=$(tput setaf 153)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BRIGHT=$(tput bold)
NORMAL=$(tput sgr0)
BLINK=$(tput blink)
REVERSE=$(tput smso)
UNDERLINE=$(tput smul)

### 0. CHECK
# 1. docker
echo
printf "%40s\n" " 0.1. checking ${BRIGHT}${GREEN}docker${NORMAL} ..."
if [ ! "$(command -v docker)" ]; then
  printf "%40s\n" "   -> Please install ${BRIGHT}${GREEN}docker${NORMAL} first: ${BLUE}${UNDERLINE}https://github.com/cccnrc/diagnosticator-mac#dependencies${NORMAL}"
  exit 1
else
  printf "%40s\n" "   -> ${BRIGHT}${GREEN}docker${NORMAL} found"
fi
# 2. docker-compose
printf "%40s\n" " 0.2. checking ${BRIGHT}${GREEN}docker-compose${NORMAL} ..."
if [ ! "$(command -v docker-compose)" ]; then
  printf "%40s\n" "   -> Please install ${BRIGHT}${GREEN}docker-compose${NORMAL} first: ${BLUE}${UNDERLINE}https://github.com/cccnrc/diagnosticator-mac#dependencies${NORMAL}"
  exit 1
else
  printf "%40s\n" "   -> ${BRIGHT}${GREEN}docker-compose${NORMAL} found"
fi
echo

我得到了这个输出:

printf 命令空格完全相同时,为什么 -> docker found 行之前的空格比 -> docker-compose found 行多得多?

颜色代码也占用字节,但不可见。你必须考虑到它们。

printf "%*s\n" \
    $((40 + ${#BRIGHT} + ${#GREEN} + ${#NORMAL})) \
    "   -> ${BRIGHT}${GREEN}docker${NORMAL} found"

在 Bash 而不是:

if [ ! "$(command -v docker)" ]

(无论如何,比 [ 更喜欢 [[,但是)更喜欢:

if hash docker 2>/dev/null

hash 将散列命令位置,这将使任何后续调用更快,因为 Bash 将不必再次查找命令。 $([ 都会产生一个子进程,这比调用内置 hash.

慢得多