Pregunta

I am writing a shell script, and would like to pipe STDOUT to a file within a su command. The outputted file needs to be owned by another user, hence the use of su. However, I can't get pipe to work with su when the text to be output and the name of the output file are variables (see below example).

My workaround is to pipe to a file without using su, then chown that file to the user I need. However, I was wondering if there's a 'single step' way of doing this using su?

Example (for illustration only):

#!/bin/sh

message="Hello World";
file="/tmp/HelloWorld.txt";

su someuser -c 'echo "${message}" > "${file}"';

If I put ${file} in double-quotes, as in this example, I get the following error:

bash: : No such file or directory

If I remove the double-quotes around ${file}, I get the following error:

bash: ${file}: ambiguous redirect
¿Fue útil?

Solución

try su someuser -c "echo \"${message}\" > ${file}";

Variables inside single quotes are not expanded.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top