Consider the following script:
#!/bin/bash
# Define a function to redirect both stdout and stderr
redirect_both_to() {
local log_file=logfile.log
exec > >(tee -a "$log_file") 2> >(tee -a "$log_file")
}
# Example functions
one() {
echo "This is from one()"
echo "Error message from one()"
}
two() {
echo "This is from two()"
echo "Error message from two()"
}
# Call the functions
function main(){
redirect_both_to
one
two
}
main "$@"
When this script is executed without sudo, the output is displayed on the console and it is written to the log file (as expected). However, if I run the same script as root (i.e., sudo ./script.sh), the script exits without printing anything to the console. But both stdout and stderr are correctly recorded in the log file. Ultimately, I want the script to be run as sudo.