通过bash中的〜/.bash_profile将目录添加到我的路径? [英] Adding directory to my path through ~/.bash_profile in bash?

查看:343
本文介绍了通过bash中的〜/.bash_profile将目录添加到我的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过〜/.bash_profile文件将目录添加到我的PATH,尽管我的Ubuntu中没有这样的文件.我有以下代码,该代码将检查人们是否拥有该文件,如果没有,将创建一个并添加所有现有路径目录和用户输入的目录.

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

问题是,如果文件已经存在,我不知道如何检查以PATH =开头的行,然后将用户输入的目录添加到该行的末尾.请注意,这只是给我的一种练习.我应该通过〜/.bash_profile将用户输入的目录添加到PATH.不过,我不知道为什么有人应该麻烦使用〜/.bash_profile将新目录添加到PATH.

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.

推荐答案

查看要添加到新.bash_profile的行:

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

第一个已经将$dr添加到PATH中,而不管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

一些注意事项:

  1. 通过touch来确保.bash_profile存在;那么您无需测试其存在.

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

只需要一行;您可以在使用export将其标记为要导出到环境中时设置一个变量.

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

$PATH中转义$,以便将文字美元符号写入.bash_profile$dr不需要这样做,因为您想让它扩展以便添加正确的目录.

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.

这篇关于通过bash中的〜/.bash_profile将目录添加到我的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆