小编Ale*_*ing的帖子

Bash:迭代变量中的行

如何在 bash 中的变量或命令输出中正确迭代行?简单地将 IFS 变量设置为新行适用于命令的输出,但不适用于处理包含新行的变量。

例如

#!/bin/bash

list="One\ntwo\nthree\nfour"

#Print the list with echo
echo -e "echo: \n$list"

#Set the field separator to new line
IFS=$'\n'

#Try to iterate over each line
echo "For loop:"
for item in $list
do
        echo "Item: $item"
done

#Output the variable to a file
echo -e $list > list.txt

#Try to iterate over each line from the cat command
echo "For loop over command output:"
for item in `cat list.txt`
do
        echo "Item: $item"
done …
Run Code Online (Sandbox Code Playgroud)

bash

304
推荐指数
5
解决办法
37万
查看次数

标签 统计

bash ×1