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}"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句