bash 循环遍历字符串列表

32 bash debian shell-script

是否可以格式化此示例:

for i in string1 string2 stringN
do
 echo $i
done
Run Code Online (Sandbox Code Playgroud)

类似于以下内容:

for i in 
string1
string2
stringN
do
 echo $i
done
Run Code Online (Sandbox Code Playgroud)

编辑:对不起,混淆,没有意识到执行脚本有不同的方法 - sh<scriptname>bash <scriptname>还有这个我现在无法命名的东西 -#!/bin/sh#!/bin/bash:)

gle*_*man 63

在 bash 中使用数组有助于提高可读性:这种数组语法允许单词之间有任意空格。

strings=(
    string1
    string2
    "string with spaces"
    stringN
)
for i in "${strings[@]}"; do
    echo "$i"
done
Run Code Online (Sandbox Code Playgroud)

  • 这看起来最优雅,但不幸的是给出错误:语法错误:“(”意外 (2认同)
  • @waayee,那么你就没有在 Bash 中运行它。请记住,“sh”不一定是 Bash,尤其是在 Debian 和 Ubuntu 上。 (2认同)

And*_*ton 8

您可以使用反斜杠转义换行符:

$ for i in \
> hello \
> world
> do
> echo $i
> done
hello
world
$
Run Code Online (Sandbox Code Playgroud)


小智 6

list='a b c d'
for element in $list;do 
    echo "$element"
done
Run Code Online (Sandbox Code Playgroud)