How Do You Troubleshoot a Linux Script Not Redirecting the Output to a File?

Problem scenario
You have a Bash script with a task that is supposed to redirect the output to a file. The command produces output when you manually run it. But the output is not getting to the file. What could be wrong?

Possible Solution
If the output of the automation has a message and the OS is Linux, the command may or may not work. The output can make it seem like the is working, but really the command is not working. Can you manually run the command and then run a subsequent command of echo $? with no quotes? If the echo $? returns a 0, then it is output (and the previous command worked). If it returns a non-zero, the output you see is an error message (and the previous command failed).

Here is an example. This command

ls nameOfFile.txt > destination.log

would not send anything to destination.log if the nameOfFile.txt was not in the current working directory. Yes, you would see output. But since the file wasn't there, the "ls nameOfFile.txt" command failed.

This would redirect the output or the error or both:

ls foobar > destination.log 2>&1

Leave a comment

Your email address will not be published.