1

I have error result of simple command:

cp -R SourceDir DestDir 2>out.txt 
result="out.txt" 

But if script haven't permission for write, how I can get error output in variable result?

2 Answers 2

4

One option is to write the file where you do have permission:

cp -R SourceDir DestDir 2>${TMPDIR:-/tmp}/out.$$.err

Another option is to capture the error (and non-error) output in a variable:

output=$(cp -R SourceDir DestDir 2>&1)
echo "$output"

Note that the first variant creates a process-specific temporary file. The file name generated thus is not very secure; if you work in a hostile environment as root, you need to take more precautions about generating easily predicted file names like that one. For most users most of the time, it is sufficient, especially if the $TMPDIR environment variable points to some directory such as $HOME/tmp where other users cannot write. Using a name containing $$ ensures that if two people run the script at the same time, they do not accidentally interfere with each other's log file.

You should also take precautions to clean up the file if the process is interrupted. The way to do that is shown in this boilerplate (template):

tmp=${TMPDIR:-/tmp}/out.$$.err
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15 # EXIT HUP INT QUIT PIPE TERM

# Command using temporary file
cp -R SourceDir DestDir 2>$tmp

# Analyse contents...

# Clean up
rm -f $tmp
trap 0
exit 0

You can exit with a non-zero status (exit $status); the key point is to remove the file and then cancel the 'trap on exit'. The signals HUP, INT, QUIT, PIPE and TERM are the most likely ones for a process to receive, and in all of those cases, the shell removes the temporary file and exits with a non-zero status (1 in the example).

Sign up to request clarification or add additional context in comments.

Comments

1
cp -R SourceDir DestDir 2>out.txt 
[ $? -eq 0 ] && { result="out.txt" } || echo 'no permission'

1 Comment

The question posits that the user does not have permission to write to out.txt, so I'm not clear how your answer helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.