Programming of any kind will always have errors, and it is sometimes difficult to pinpoint where in the coding it occurred.
A way to save errors to a file is done with redirection.
A good habit to consider.
One feature bash has is something called the bit bucket. It is one of the several pseudo-devices available to programmers.
The one we will be discussing here is /dev/null.
/dev/null is a special virtual device of no data or content. If data is sent to it (redirected), it's discarded. If data is read from it (redirected), it is null/empty.
It essentially suppresses program output.
So, what good is a device that throws everything away we send to it, or provides us with nothing to use?
Good question. /dev/null is used in cases where you don't need or want to actually see the response, but do need to act on it.
In a directory that contains files or directories, issue the command:
ls > /dev/null
You should NOT see any output.
echo "Hey stupid" > /dev/null
Same
However, if the command produced an error, you would see this result:
ls ThisFileDoesNotExist > /dev/null ls: ThisFileDoesNotExist: No such file or directory
We did NOT redirect STDERR to /dev/null, so we need one of these file descriptors.
Whenever you execute a program, the operating system always opens three files, standard input, standard output, and standard error.
Logging errors to a file is done using 2 redirects:
The file descriptors are the digits (0, 1, 2)
The way we can send error messages to a file requires the use of the file descriptor 2 and the special character &:
ls ThisFileDoesNotExist ls: ThisFileDoesNotExist: No such file or directory ls ThisFileDoesNotExist > /dev/null ls: ThisFileDoesNotExist: No such file or directory ls ThisFileDoesNotExist > /dev/null 2>&1
The last example above used redirection to the bit bucket AND redirection of STDERR and STDOUT as well - so nothing was seen.
Be careful with the 2>&1 construction:
A good reference to this is found at Medium.
And every time we execute a command, it returns an exit status, which the system understands.
If the result of a command is successful, the exit status is 0, otherwise it is something greater than 0.
We can check the value of the exit status by using the variable $?. It holds the exit value of the last program the shell executed.
echo $? 1