Q: I need to run a command with sudo and redirect the output, but it is failing when writing to the output file:
$ sudo ioscan -f > /var/adm/ioscan.log
su: /var/adm/ioscan.log: Cannot create the specified file.
A: sudo is processing the command line but the “>” character for redirect is processed by your shell, not sudo. So your shell can’t write to /var/adm. You can try sending the entire line to a subshell like this:
$ sudo ksh -c “ioscan -f > /var/adm/ioscan.log”
Then the subshell will be privileged by sudo and the entire line (including redirect) runs at the elevated user ID. But this can get complicated with other special characters such as imbedded “text” strings. Here is an easy way to write to a file without using shell redirects:
$ sudo ioscan -f | tee /var/adm/ioscan.log > /dev/null
or to append to a file:
$ sudo ioscan -f | tee -a /var/adm/ioscan.log > /dev/null
The tee command takes stdin from the pipe and writes it to stdout and also to the named file. sudo covers the tee command through the pipe. But an undesired side effect is that tee echoes stdin to stdout. To use tee as a simple writer, redirect stdout to /dev/null. In this case, sudo isn’t needed for the shell redirect: > /dev/null
– See more at: http://serviceitdirect.com/blog/sudo-redirect-fails#sthash.6wLIg15K.dpuf
Tags: HP-UX