bashshell脚本:写入文件无效

bashshell脚本:写入文件无效,bash,shell,ubuntu,Bash,Shell,Ubuntu,我对shell脚本非常陌生,我正在尝试将字符串变量的内容写入文件。当我在使用变量写入文件之前回显变量时,它工作得很好。但是当脚本完成时,不会对文件进行更新 我的代码是: echo $str touch $HOME/Documents/config.txt sudo chmod u+w $HOME/Documents/config.txt echo "$str" >> sudo $HOME/Documents/config.txt sudo cp

我对shell脚本非常陌生,我正在尝试将字符串变量的内容写入文件。当我在使用变量写入文件之前回显变量时,它工作得很好。但是当脚本完成时,不会对文件进行更新

我的代码是:

    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!"

我尝试过给它写权限,不同的文件写入方式。同样在前面,我认为,.ssh文件夹是我的问题的根源,正如您所看到的,我首先尝试在其他地方写入文件,然后尝试将其移动到.ssh文件夹。但无论我在哪里尝试编写,文件的结尾仍然是空的。

从这里删除
sudo

echo "$str" >> sudo $HOME/Documents/config.txt
您正在将echo的输出管道化到文件中
sudo
用于以root权限运行命令


如果您没有文件的写入权限:

因为您触摸了该文档,所以它属于您。这意味着您根本不必使用
sudo
。您必须从脚本中删除
sudo
的所有痕迹

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!"