How to make a bash_profile function acts different

2019-09-08 09:57发布

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条回答
Root(大扎)
2楼-- · 2019-09-08 10:17

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
查看更多
登录 后发表回答