1

I have command

store=`stat /some/path`
echo ${store}>>file.txt

then I echo the variable result in a file

Sometimes the file doesn't exists and I get an error as stat: cannot stat xxxx

However, when this error occurs, it is echoed to the stdout than stored in my variable. I would like even the error to be printed out. How can I capture the same?

CoderBC
  • 1,262
  • 2
  • 13
  • 30
  • 1
    Your code has multiple issues; I might suggest using http://shellcheck.net perhaps and get some tips... – l'L'l Jun 22 '16 at 03:19
  • Not actually to stdout, no -- it's going to *stderr* rather than to your file. – Charles Duffy Jun 22 '16 at 03:24
  • BTW, what are you accomplishing with `store=$(stat /some/path); echo ${store} >>file.txt` that you couldn't accomplish with `stat /some/path >>file.txt` (the latter with a `2>&1` if you want to redirect stderr as well) – Charles Duffy Jun 22 '16 at 03:26

1 Answers1

1

You don't.

You don't "capture" the error message I mean. Instead you check if the file exist before doing all this:

my_path="/some/path"
if [ -f "$my_path" ]; then
    stat "$my_path" >> file.txt
fi

It should be noted that there is a race-condition here: The file could be removed between the check and the stat command. The chances for that happening are small, but it can still happen.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    Needs more quotes. And if the OP wants to redirect their stderr to a file (per the description, it sounds like that file is for human review), well, why not tell them how to do that? – Charles Duffy Jun 22 '16 at 03:19
  • 2
    Also, suggesting all-caps variable names is bad form. See http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html -- that namespace is reserved for variables with meaning to the shell or operating system; application-defined names should have at least one lower-case alpha character to avoid potential conflicts, as a shell variable will overwrite any like-named environment variable. – Charles Duffy Jun 22 '16 at 03:20
  • 1
    ...re: "more quotes" -- `[ -f "$my_path" ]`, and `stat "$my_path"` -- otherwise, if it's a filename that contains spaces or globs it can be modified before being passed to `test` (in the former case) or `stat` (in the latter). – Charles Duffy Jun 22 '16 at 03:22
  • 2
    If the goal is to check, then `if ! stat "$my_path"; then : "failure case here"; fi` would be a way to retrieve the data or fail and retrieve the knowledge that it failed in an atomic operation. – Charles Duffy Jun 22 '16 at 03:23