Search code examples
bashroot

create / edit file in bash with root privileges


I am creating then writing to a file in bash4, in a directory with root privileges.

I looked at these results from stackoverflow: https://unix.stackexchange.com/questions/37875/how-to-add-a-line-to-a-file-which-has-only-root-write-permission-and-to-continue

But not helping me. Below $fName contains path to file.

First I touch the file: sudo touch $fName;

I am writing a key value pair (YAML) and this works:

echo " "$key": "$value

But when I try to write to the file $fName as in:

sudo sh -c 'echo "  "$key": "$value >> $fName';

or even:

sudo sh -c 'echo \"  "$key": "$value\ >> $fName';

does not work.

Get various errors:

Bad substitution, command not found etc.

I was also trying to write to memory or /tmp and then move it to the directory.

Would that be a better idea? Somehow that did not work either.

Thank you for your help.


Solution

  • all things including variables will be regard as string but not variable!

    Does this work? sudo sh -c "echo \" $key: $value \" >> $fName"