Reputation: 61
I have a script that performs many different operations and displays the status of their completion in a clear way for the user. I need a function so that some strings can be retrieved as variables for further processing. This is a highly simplified example:
#!/bin/bash
echo "Test script."
echo -n "1) cat file "
cat ./testfile.f &> /dev/null
if [ $? -eq 0 ]
then
echo "$(tput hpa $(tput cols))$(tput cub 8)[OK]"
else
echo "$(tput hpa $(tput cols))$(tput cub 8)[FAIL]"
fi
echo -n "2) make subfolder "
mkdir ./testdir &> /dev/null
if [ $? -eq 0 ]
then
echo "$(tput hpa $(tput cols))$(tput cub 8)[OK]"
else
echo "$(tput hpa $(tput cols))$(tput cub 8)[FAIL]"
fi
It take some as:
$./test.sh
Test script.
1) cat file [FAIL]
2) make subfolder [OK]
How can I get the last line (ideally, any string) during script execution? Ideally it would be using a function (so I could work with the resulting string) This string will be processed in the same script. So far, I see only one solution: redirect the output of each echo command using tee.
Is there any way to read the already outputted data!?
Upvotes: 2
Views: 802
Reputation: 20032
Suppose that you have strings {1..5} that you need to process:
process() {
while read -r input; do
sleep 2
echo "Processed ${input}."
done
}
printf "line %s\n" {1..5} | process
In this situation you might want to see the numbers before they are being processed.
You can do this by duplicating stdout to fd 3
and use a function.
display() {
while read -r input; do
echo "=== ${input} ===" >&3
echo "${input}"
done
}
process() {
while read -r input; do
sleep 2
echo "Processed ${input}."
done
}
exec 3>&1
printf "line %s\n" {1..5} | display | process
Upvotes: 1