如何使 bash_profile 函数在 bash_profile 内或以后由用户调用时表现不同 运行?

How to make a bash_profile function acts different running within bash_profile or later called by user?

我的意思是,在~/.profile中,一个函数doit会在用户登录时说Welcome,但当用户稍后执行doit时会说其他话。

doit() {
    if some_test_here; then
        echo "Running within ~/.profile. Welcome."
    else
        echo "Called by user."
    fi
}

doit

我认为 ~/.profile 在 Mac 上比 ~/.bash_profile 在 Linux 上更好。所以我用 ~/.profile 作为例子。

传递参数或检查环境的两种方法。


使用仅由 .profile 中的调用使用的参数。

doit () {
    if [ "${1:-onlogin}" -eq onlogin ]; then
        echo "Running from .profile"
    else
        echo "Called by user"
    fi
}

doit onlogin  # from .profile
doit          # ordinary call

检查 .profile 设置的变量的环境

doit () {
  if [ "${_onlogin}" ]; then
    echo "Running from .profile"
  else
    echo "Called by user"
  fi
}

onlogin=1 doit    # from .profile; value can be any non-empty string
doit              # ordinary call