How to Catch Standard Error to a Variable in Bash
To store stderr into a variable we need to use command substitution.
But, by default, command substitution only catches the standard output(stdout). To capture stderr we need to use 2>&1 redirector.
Following example, will store both stdout and stderr into the $VAR variable.
VAR=$(cat file1.txt nofile.txt 2>&1) echo $VAR
To get standard errors only, we need to redirect stdout to the "/dev/null" file.
Following example will get stderr into the $ERROR variable and discard the stdout.
ERROR=$(cat file1.txt nofile.txt 2>&1 > /dev/null) echo $ERROR