I want to redirect the output of a for loop to a file and to stdout.
So far I tried this but it actually forks the script :
$ cat myScript.sh
#!/usr/bin/env bash
myVar1=X.Y.Z.T
echo "=> BEFORE THE LOOP : myVar1 = $myVar1"
for IP;do
myVar1="$IP"
echo "=> INSIDE THE LOOP : myVar1 = $myVar1"
done 2>&1 | tee -a myFile.log
echo "=> AFTER THE LOOP : myVar1 = $myVar1"
EDIT1 : If I run the script, here is what happens :
$ ./myScript.sh 1.2.3.4 9.8.7.6
=> BEFORE THE LOOP : myVar1 = X.Y.Z.T
=> INSIDE THE LOOP : myVar1 = 1.2.3.4
=> INSIDE THE LOOP : myVar1 = 9.8.7.6
=> AFTER THE LOOP : myVar1 = X.Y.Z.T
The value of myVar1
is not the same in the father process than in the child process.
How can I avoid using a pipe here ?
EDIT0 : After some research in the chapter 20 section 1 of the Advanced Bash-Scripting Guide, I came up with this :
exec 3>&1 1> >(tee -a myFile.log) # backup stdout to file descriptor 3 and then redirect stdout to myFile.log via process substitution
# my shell instructions are here
exec 1>&3 3>&- # restore stdout and close file descriptor 3