How to get error output and store it in a variable or file

后端 未结 3 1699
耶瑟儿~
耶瑟儿~ 2021-01-14 11:31

I\'m having a little trouble figuring out how to get error output and store it in a variable or file in ksh. So in my script I have cp -p source.file destination

相关标签:
3条回答
  • 2021-01-14 11:57

    You can redirect the error output of the command like so:

    cp -p source.file destination 2>> my_log.txt
    

    It will append the error message to the my_log.txt file.

    In case you want a variable you can redirect stderr to stdout and assign the command output to a variable:

    my_error_var=$(cp -p source.file destination 2>&1)
    
    0 讨论(0)
  • 2021-01-14 11:58

    You can do STDERR redirects by doing:

    command 2> /path/to/file.txt
    
    0 讨论(0)
  • 2021-01-14 12:00

    In ksh (as per Q), as in bash and other sh derivatives, you can get all/just stderr output from cp using redirection, then grabbing in a var (using $(), better than backtick if using a vaguely recent version):

    output=$(cp -p source.file destination 2>&1)
    

    cp doesn't normally output anything though this would capture stdout and stderr; to capture just stderr this way, use 1>/dev/null also. The other solutions redirecting to a file could use cat/various other commands to output/process the logfile.

    Reason why I don't suggest using outputting to temporary files:

    Redirecting to a file then reading that in (via read command or more inefficiently via $(cat file) ), particularly for just a single line, is less efficient and slower; though not so bad if you want to append to it each time for multiple operations before displaying the errors. You'll also leave the temporary file around unless you ALWAYS clear it up, don't forget when people interrupt (ie. Ctrl-C) or kill the script.

    Using temporary files also could be a problem if the script is run multiple times at once (eg. could happen via cron if filesystem/other delays cause massive overruns or just from multiple users), unless the temporary filename is unique.

    Generating temporary files is also a security risk unless done very carefully, especially if the file data is processed again or the contents could be rewritten before display by something else to confuse/phish the user/break the script. Don't get into a habit of doing it too casually, read up on temporary files (eg. mktemp) first via other questions here/google.

    0 讨论(0)
提交回复
热议问题