Reload .profile in bash shell script (in unix)?

后端 未结 5 1765
有刺的猬
有刺的猬 2021-01-29 22:29

I\'m new to bash shell scripting, and have come across a challenge. I know I can reload my \".profile\" file by just doing:

. .profile

but I\'m

相关标签:
5条回答
  • 2021-01-29 23:06

    Try this:

    cd 
    source .bash_profile
    
    0 讨论(0)
  • 2021-01-29 23:08

    A couple of issues arise when trying to reload/source ~/.profile file. [This refers to Ubuntu linux - in some cases the details of the commands will be different]

    1. Are you running this directly in terminal or in a script?
    2. How do you run this in a script?

    Ad. 1)

    Running this directly in terminal means that there will be no subshell created. So you can use either two commands:

    source ~/.bash_profile
    

    or

    . ~/.bash_profile
    

    In both cases this will update the environment with the contents of .profile file.

    Ad 2) You can start any bash script either by calling

    sh myscript.sh 
    

    or

    . myscript.sh
    

    In the first case this will create a subshell that will not affect the environment variables of your system and they will be visible only to the subshell process. After finishing the subshell command none of the exports etc. will not be applied. THIS IS A COMMON MISTAKE AND CAUSES A LOT OF DEVELOPERS TO LOSE A LOT OF TIME.

    In order for your changes applied in your script to have effect for the global environment the script has to be run with

    .myscript.sh
    

    command.

    In order to make sure that you script is not runned in a subshel you can use this function. (Again example is for Ubuntu shell)

    #/bin/bash
    
    preventSubshell(){
      if [[ $_ != $0 ]]
      then
        echo "Script is being sourced"
      else
        echo "Script is a subshell - please run the script by invoking . script.sh command";
        exit 1;
      fi
    }
    

    I hope this clears some of the common misunderstandings! :D Good Luck!

    0 讨论(0)
  • 2021-01-29 23:16

    Try:

    #!/bin/bash
    # .... some previous code ...
    # help set exec | less
    set -- 1 2 3 4 5  # fake command line arguments
    exec bash --login -c '
    echo $0
    echo $@
    echo my script continues here
    ' arg0 "$@"
    
    0 讨论(0)
  • 2021-01-29 23:22

    The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

    0 讨论(0)
  • 2021-01-29 23:23

    Try this to reload your current shell:

    source ~/.profile
    
    0 讨论(0)
提交回复
热议问题