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

后端 未结 10 1229
深忆病人
深忆病人 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:34

    If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>. A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

    LINE='include "/configs/projectname.conf"'
    FILE=lighttpd.conf
    grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"
    

提交回复
热议问题