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

非 Y 不嫁゛ 提交于 2019-12-13 06:16:48

问题


I mean, in ~/.profile, a function doit will say Welcome when user login, but say other words when user execute doit later.

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

doit

I think ~/.profile is better on Mac for ~/.bash_profile on Linux. So I use ~/.profile as example.


回答1:


Two ways to are to pass an argument, or to check the environment.


Use an argument that is only used by the call in .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

Check the environment for a variable set by .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


来源:https://stackoverflow.com/questions/40281964/how-to-make-a-bash-profile-function-acts-different-running-within-bash-profile-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!