首页 > 解决方案 > 在花括号中的“while”循环中分配变量不起作用

问题描述

bash 脚本获取参数、排序、修改并将它们输出到文件中。我也尝试将最后一个排序的参数保存在变量中,但它不起作用。变量为空。变量的分配在花括号内的管道“while 循环”内。

我试过在脚本开头引入变量,它没有效果。

#!/bin/bash

# Set work dir to place where the script located
cd "$(dirname "$0")"

# Read args
for arg in "$@"
do    
    echo "$arg"
done | sort | { 
while read -r line 
do  
    echo "$line" + "modifier"
    last_sorted_arg="$line" # It does not work
done } > sorted_modified_args.txt


# Empty string - not Ok
echo "$last_sorted_arg"

sleep 3

我可以使用一个临时文件和两个循环来解决它,但它看起来不太好。有没有办法在没有临时文件和两个循环的情况下做到这一点?

#!/bin/bash

cd "$(dirname "$0")"

for arg in "$@"
do    
    echo "$arg"
done | sort > sorted_args.txt


while read -r line 
do  
    last_sorted_arg="$line"
done < sorted_args.txt

# Ok
echo "$last_sorted_arg"


# It works too
while read -r line 
do  
    echo "$line" + "modifier"
done < sorted_args.txt > sorted_modified_args.txt

sleep 3

标签: bash

解决方案


局部变量在子进程中丢失。

编辑:删除了不工作的代码,试图让事情接近原始代码。

排序可以以不同的方式进行:

#!/bin/bash

last_sorted_arg=$( printf "%s\n" "$@" | sort -n | tee sorted_modified_args.txt | tail -1)
echo "last=${last_sorted_arg}"

推荐阅读