Appending a line to a file only if it does not already exist

后端 未结 10 1230
深忆病人
深忆病人 2020-11-30 16:44

I need to add the following line to the end of a config file:

include \"/configs/projectname.conf\"

to a file called lighttpd.conf

10条回答
  •  被撕碎了的回忆
    2020-11-30 17:22

    Using sed: It will insert at the end of line. You can also pass in variables as usual of course.

    grep -qxF "port=9033" $light.conf
    if [ $? -ne 0 ]; then
      sed -i "$ a port=9033" $light.conf
    else
        echo "port=9033 already added"
    fi
    

    Using oneliner sed

    grep -qxF "port=9033" $lightconf || sed -i "$ a port=9033" $lightconf
    

    Using echo may not work under root, but will work like this. But it will not let you automate things if you are looking to do it since it might ask for password.

    I had a problem when I was trying to edit from the root for a particular user. Just adding the $username before was a fix for me.

    grep -qxF "port=9033" light.conf
    if [ $? -ne 0 ]; then
      sudo -u $user_name echo "port=9033" >> light.conf
    else
        echo "already there"    
    fi
    

提交回复
热议问题