Adding directory to my path through ~/.bash_profile in bash?

末鹿安然 提交于 2019-12-12 01:59:49

问题


I want to add a directory to my PATH through the ~/.bash_profile file, though I don't have a file like this in my Ubuntu. I have the following code, which will check whether people have that file or not, and if not will create one and add all the existing path directories and the one entered by the user.

#!/bin/bash

echo "Please enter a directory that you want to add to your PATH: "
read dr

if [ -f ~/.bash_profile ]
then
    # Add the read 'dr' directory to the end of the line that starts 
    # with PATH=, in your ~/.bash_profile file
    source ~/.bash_profile
else
    echo "PATH=$PATH:$dr" > ~/.bash_profile
    echo "export PATH" >> ~/.bash_profile
    source ~/.bash_profile
fi

The point is that, if the file already exists, I don't know how can I check to find the line that starts with PATH=, and then add the directory entered by the user to the end of that line. Please note that this is just an exercise given to me. I should add a directory entered by the user to the PATH through ~/.bash_profile. Though, I don't know why someone should bother to use ~/.bash_profile to add new directory to the PATH.


回答1:


Look at the lines you are adding to a new .bash_profile:

echo "PATH=$PATH:$dr" > ~/.bash_profile
echo "export PATH" >> ~/.bash_profile

The first one already adds $dr to the PATH, regardless of what is already in PATH. This means you can do the same thing even if .bash_profile already exists: just tack on a new line that appends yet another directory:

touch ~/.bash_profile
echo "export PATH=\$PATH:$dr" >> ~/.bash_profile

A few things to note:

  1. Ensure that .bash_profile exists by touching it; then you don't need to test for its existence.

  2. Only one line is needed; you can set a variable when you use export to mark it for export to the environment.

  3. Escape the $ in $PATH so that a literal dollar sign is written to .bash_profile; the same is not needed for $dr because you want to let that expand so the proper directory is added.

  4. Append this new line using >>, so you don't overwrite the existing file.




回答2:


~/.bashrc 

Try this file in home.



来源:https://stackoverflow.com/questions/15508892/adding-directory-to-my-path-through-bash-profile-in-bash

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