如何在 Bash 循环中只显示一次 echo 命令

How to display only once echo command in a Bash loop

我的问题很简单。我有 :

a=$(echo "lol")

for i in {1..3}; 
do 
echo $a && echo $i ; 
done

我得到:

lol
1
lol
2
lol
3

我只想在输出的开头打印一次变量 a ,以获得 :

lol
1
2
3

有什么想法吗?

将 echo 移到 for 循环之外

a=$(echo "lol")

echo $a
for i in {1..3}; do 
    echo $i; 
done

或:

echo "lol"
for i in {1..3}; do 
    echo $i; 
done

test run in shell

我建议:

#!/bin/bash

a="lol"$'\n'      # append newline

for i in {1..3}
do
  echo -e "$a$i"  # -e: enable interpretation of escape sequences
  unset a
done

或者替换成你的问题

echo $a && echo $i ;

[[ "$i" == "1" ]] && echo "$a"
echo "$i"

参见:help echohelp unset

你根本不需要循环

a=$(echo "lol") # Not sure why poster wrote this rater than a=lol

printf %s\n "$a" {1..3}