繁体   English   中英

无法使用脚本写入文件

[英]Can't write to file with script

我编写了一个脚本,它应该运行一些命令,重新启动我的 ubuntu 服务器,然后在服务器启动后,恢复操作,并从 bash 文件中删除条目。

我已经尝试了几个小时来弄清楚为什么我的脚本不会写入 .bashrc (或任何文件)。 单独测试命令工作得很好。 但是,当通过我的脚本运行时,不会将任何内容写入文件。 在这一点上,我被难住了,真的很想有一双新的眼睛来帮忙,因为我确信原因很愚蠢,可能是我缺少的东西。 如果这最终成为一个愚蠢的问题,这将是我的第一个脚本非常抱歉。 我将“sudo reboot 命令放在评论中,这样我就不必每次都重新启动。

该脚本的名称是 test.sh,从 ~/. 我希望这很清楚,我没有错过任何事情。

#!/bin/bash

echo "Script initiating"

#condition for script to run after reboot, created later on
if [ ! -f /var/run/bootflag ]; then
        echo "First run"
        script="bash ~/test.sh"
        #this will add the script in the bash file so it will be ran on next boot
        echo "$script" >> ~/.bashrc

        echo "bash entry added"
        #creating flag file to check if this is a second run
        sudo touch /var/run/bootflag
        echo "Flag created"
        echo "Rebooting..."
        #sudo reboot
else
        echo "resuming script..."
        echo "cleaning up..."
        #remove the bash entry by replacing it with a space
        sed -i '/bash/d' ~/.bashrc


        echo "bash entry removed"
        #remove the boot flag
        sudo rm -f /var/run/bootflag

        echo "bootflag removed"
        echo "running commands post-reboot"
        #commands here
        echo "script exiting"
fi

我终于弄明白了。

因为我使用 sudo 运行脚本,所以脚本将采用 root 用户的相对路径~/.bashrc 该脚本一直运行良好,我只是在查看我的用户的 .bashrc 并期待事情会出现,而一直在写入 root 用户的 .bashrc 文件。

脚本中使用了sudo来处理所有提升的命令,并在没有sudo的情况下正常运行脚本,它就在那里,按预期工作。

正如我所想,这毕竟是愚蠢的。 至少我今天学到了一些东西。

谢谢大家花时间回复和帮助,我真的很感激。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM