The bash script gets arguments, sort, modify and output them in the file. I also try to save the last sorted argument in the variable, but it does not work. The variable is empty. The assignment of the variable is within piped "while loop" that within curly braces.
I have tried introduce the variable at begin of the script, it has no effect.
#!/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
I can use a temporary file and two loops to work around it, but it looks not so good. Is there a way to do it without a temporary file and two loops?
#!/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