【问题标题】:bash shell script: writing to file does not workbash shell 脚本:写入文件不起作用
【发布时间】:2017-07-18 00:56:39
【问题描述】:

我是 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 文件夹。但是无论我在哪里尝试它,文件最后仍然是空的。

【问题讨论】:

    标签: bash shell ubuntu


    【解决方案1】:

    既然你touch-ed 了这份文件,它就属于你了。这意味着您根本不必使用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!"
    

    【讨论】:

      【解决方案2】:

      从这里删除sudo

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

      您正在将 echo 的输出通过管道传输到文件中。 sudo 用于以 root 权限运行命令。

      如果您没有文件的写入权限:How do I use sudo to redirect output to a location I don't have permission to write to?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-10
        • 2015-03-13
        • 2011-10-14
        相关资源
        最近更新 更多