bash - 在花括号中的“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
解决方案
局部变量在子进程中丢失。
编辑:删除了不工作的代码,试图让事情接近原始代码。
排序可以以不同的方式进行:
#!/bin/bash
last_sorted_arg=$( printf "%s\n" "$@" | sort -n | tee sorted_modified_args.txt | tail -1)
echo "last=${last_sorted_arg}"
推荐阅读
- visual-studio - Visual Studio 中的建议重叠
- sed - sed 模式匹配,在第一个找到的字符处停止
- javascript - Joi 验证器替代模式错误消息
- python - Python PuLP:保持变量之间的相对关系
- angular - *ngFor 带子数组
- persistence - 带有 Azure CosmosDB 的 MassTransit Saga Persistence 不适用于具有指定分区键的容器
- jmeter - 如何在 JMeter 中清除采样器的缓存
- python-3.x - 固定大小的 QGraphicsView 和 QGraphicsScene
- ms-access - Ms Access 如何将字符串 HH:MM 转换为数字或时间进行计算
- r - 根据 R 中的单元格值和列名查找行名