1

I am super new to shell scripting and I am trying to write the contents of my string variable to file. When I echo the variable before using it to write into the file, it works well. But when the script is completed, there is no update to the file.

My code is:

    echo $str
    touch $HOME/Documents/config.txt
    sudo chmod u+w $HOME/Documents/config.txt
    echo "$str" >> sudo $HOME/Documents/config.txt
    sudo cp sudo $HOME/Documents/config.txt $HOME/.ssh/
    echo $str
    echo "configuration file updated!"

I have tried giving it write permission, different ways of writing to the file. Also earlier I thought, .ssh folder is the source of my problem so as you can see, I am first trying to write the file somewhere else and then trying to move it to the .ssh folder. But wherever I try to rite it, file is still empty at the end.

Kenster
  • 23,465
  • 21
  • 80
  • 106
chavo108
  • 13
  • 3

2 Answers2

1

Remove sudo from here:

echo "$str" >> sudo $HOME/Documents/config.txt

You're piping the output of echo into the file. sudo is used to run a command with root privileges.

If you don't have write permissions to the file: How do I use sudo to redirect output to a location I don't have permission to write to?

Felix Guo
  • 2,700
  • 14
  • 20
1

Since you touch-ed the document, it belongs to you. That means you don't have to use sudo at all. You have to remove all traces of sudo from your script.

echo $str
touch $HOME/Documents/config.txt
chmod u+w $HOME/Documents/config.txt
echo "$str" >> $HOME/Documents/config.txt
cp $HOME/Documents/config.txt $HOME/.ssh/
echo $str
echo "configuration file updated!"
Eugene Chow
  • 1,688
  • 1
  • 11
  • 18