Bash脚本:如果该行尚不存在,则仅对〜/ .bash_profile回显一行

ma1*_*w28 3 bash shell scripting grep sed

我写了一个bash git-install脚本.到最后,我做:

echo "Edit ~/.bash_profile to load ~/.git-completioin.bash on Terminal launch"
echo "source ~/.git-completion.bash" >> ~/.bash_profile
Run Code Online (Sandbox Code Playgroud)

问题是,如果你运行该脚本超过一次,你最终多次追加这一行到〜/ .bash_profile.如何使用使用bash脚本grep或者sed(或者你可以推荐另一种选择),只添加行,如果它还没有在文件中存在.另外,~/.profile如果该文件存在~/.bash_profile且不存在,我想添加该行,否则只需将其添加到~/.bash_profile.

cam*_*amh 11

这样的事情应该这样做:

LINE_TO_ADD=". ~/.git-completion.bash"

check_if_line_exists()
{
    # grep wont care if one or both files dont exist.
    grep -qsFx "$LINE_TO_ADD" ~/.profile ~/.bash_profile
}

add_line_to_profile()
{
    profile=~/.profile
    [ -w "$profile" ] || profile=~/.bash_profile
    printf "%s\n" "$LINE_TO_ADD" >> "$profile"
}

check_if_line_exists || add_line_to_profile
Run Code Online (Sandbox Code Playgroud)

几个笔记:

  • 我用的.命令,而不是source作为source一个bashism,但.profile可以通过非bash的外壳中.该命令source ...是错误的.profile
  • 我用过printf而不是echo因为它更便携,并且不会像bash那样搞砸反斜杠转义的字符echo.
  • 尝试对非明显的失败更加强大.在这种情况下,确保.profile存在并且在尝试写入之前是可写的.
  • grep -Fx用来搜索字符串.-F意味着固定字符串,因此搜索字符串中的特殊字符不需要转义,并且-x仅表示匹配整行.这-qs是常见的grep语法,用于检查字符串的存在而不显示它.
  • 这是概念的证明.我实际上并没有这样做.我很糟糕,但是星期天早上我想出去玩.


Way*_*uin 6

if [[ ! -s "$HOME/.bash_profile" && -s "$HOME/.profile" ]] ; then
  profile_file="$HOME/.profile"
else
  profile_file="$HOME/.bash_profile"
fi

if ! grep -q 'git-completion.bash' "${profile_file}" ; then
  echo "Editing ${profile_file} to load ~/.git-completioin.bash on Terminal launch"
  echo "source \"$HOME/.git-completion.bash\"" >> "${profile_file}"
fi
Run Code Online (Sandbox Code Playgroud)