如何在 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 ×1