问题
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:
Ensure that
.bash_profile
exists bytouch
ing it; then you don't need to test for its existence.Only one line is needed; you can set a variable when you use
export
to mark it for export to the environment.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.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