0

在 bash 中,我想根据终端中的当前行是否为空来有条件地回显一个新行。

比如说,first.sh先运行,但我不控制它,也不知道它每次会打印什么。我可以让second.sh始终在全新的行上开始打印并且不要在其上方留下任何空白行吗?

第一个.sh

#!/bin/bash

let "n = 1"
max=$((RANDOM%3))
while [ "$n" -le "$max" ]
do
  printf "%s" x
  let "n += 1"
done

第二个.sh

#!/bin/bash

#if [ not_in_first_terminal_column ]
#  echo
#fi
echo "Hola"

我想要以下输出之一

$ ./first.sh && ./second.sh
Hola
$ ./first.sh && ./second.sh
x
Hola
$ ./first.sh && ./second.sh
xx
Hola

但不是

$ ./first.sh && ./second.sh

Hola
$ ./first.sh && ./second.sh
xHola
$ ./first.sh && ./second.sh
xxHola

有可能做我想做的事吗?我想使用 ANSI 转义码,就像在这里一样,但我还没有找到办法。

4

1 回答 1

0

如果变量不为空,请使用 -n 测试变量的值:

[[ -n $VAR ]] && echo "$VAR"

# POSIX or Original sh compatible:

[ -n "$VAR" ] && echo "$VAR"

# With if:

if [[ -n $VAR ]]; then
   echo "$VAR"
fi

if [ -n "$VAR" ]; then
   echo "$VAR"
fi

它实际上相当于[[ $VAR != "" ]]or ! [ "$VAR" = "" ]

此外,在 Bash 中,如果它只填充空格,您可以对其进行测试:

shopt -s extglob  ## Place this somewhere at the start of the script

[[ $VAR == +([[:space:]]) ]] && echo "$VAR"

if [[ $VAR == +([[:space:]]) ]]; then
     echo "$VAR"
fi

如果它更有帮助,请使用[[:blank:]]仅匹配空格和制表符而不是换行符等。

如果要从输入文件或管道中删除空行,可以使用其他工具,如 sed:

sed -ne '/^$/!p' file... | sed -ne '/^[[:space:]]*$/!p'

于 2013-08-15T06:54:31.370 回答