关于在linux下linux添加硬盘PATH ,我知道要把它放在./bash_profile或者是./bashrc中,但是具体怎么linux添加硬盘呢?

Linux-profile、bashrc、bash_profile之间的区别和联系 - John_ABC - 博客园
随笔 - 385, 文章 - 0, 评论 - 9, 引用 - 0
为使Bash更好地为我们服务,我们需定制bash shell环境。
~/.bash_profile、~/.bashrc、和~/.bash_logout
上面这三个文件是bash shell的用户环境配置文件,位于用户的主目录下。其中.bash_profile是最重要的一个配置文件,它在用户每次登录系统时被读取,里面的所有命令都会被bash执行。.profile(由Bourne Shell和Korn Shell使用)和.login(由C Shell使用)两个文件是.bash_profile的同义词,目的是为了兼容其它Shell。在Debian中使用.profile文件代 替.bash_profile文件。
.bashrc文件会在bash shell调用另一个bash shell时读取,也就是在shell中再键入bash命令启动一个新shell时就会去读该文件。这样可有效分离登录和子shell所需的环境。但一般 来说都会在.bash_profile里调用.bashrc脚本以便统一配置用户环境。
.bash_logout在退出shell时被读取。所以我们可把一些清理工作的命令放到这文件中。
在 /etc目录的bashrc和profile是系统级(全局)的配置文件,当在用户主目录下找不到.bash_profile 和.bashrc时,就会读取这两个文件。.bash_history是bash shell的历史记录文件,里面记录了你在bash shell中输入的所有命令。可通过HISSIZE环境变量设置在历史记录文件里保存记录的条数。alias l = 'ls -l'是设置别名的语句,把它放在这些配置文档中就可使我们能用简单的'l'命令,代替'ls -l'命令。
当我们修改了这些配置件后,可用source .bash_profile命令使它修改内容马上生效。
运行中的Bash有两种属性(状态/模式),一种,是否interactive shell(交互式Shell),另一种,是否login shell(登录Shell),然后,运行中的Shell排列组合有这么几种:
  登录交互式Shell、非登录交互式Shell、登录非交互式Shell、非登录非交互式Shell
交互式Shell:没有非选项参数,没有-c,标准输入和标准输出与终端相连的,或者用-i参数启动的Bash实例。可以通过探测PS1变量是否设置或者$-返回值中是否包含字幕i来判定。什么是没有非选项参数?比如bash ~/myscript/clear_temp_files.sh这样执行的Shell脚本的Bash实例,就不是交互式Shell,因为脚本的路径,就是非选项参数。-c又是干什么的?就是使用一个字符串作为Bash的传入参数,比如bash -c &ls -ahl&,这种Shell进程也不算是交互式Shell。
登录Shell:第0个参数以-号开头的Bash实例,或者用-login参数启动的Bash Shell。更加诡异了,什么叫第0个参数以-号开头?你只要随便登录一个*nix系统,Mac也行,Linux也行,然后echo $0,你就明白了,惊讶吧,出来的值竟然是-bash。真的是以-号开头的!!&
登录Shell(不管是不是交互式的)文件加载顺序如下:
/etc/profile
~/.bash_profile
~/.bash_login
~/.profile
交互式非登录Shell文件加载顺序如下:
/etc/bashrc
一个crontab脚本,没经过处理的话,既不是交互式Shell,也不是登录Shell,所以上面的都不会执行。怎么处理?比如可以把shabang改一下#!/bin/bash -l让脚本用登录Shell来解释执行,就可以加载/etc/profile或者,调用Bash解释器,加-l参数也可以。
另一个遇到的问题,为什么在Linux,我们总是配置~/.bashrc但是在Mac下,我们配置就没有用呢,要去配置~/.bash_profile才行?哈!什么情况加载~/.bashrc,上面说得很清楚了,交互式非登录Shell,那在Mac下,你打开Term,echo一下$0,看看,前面是不是有个-号?说明这是交互式的登录Shell,当然不会加载~/.bashrc了。实属正常。你肯定要问了,为啥Linux下没问题呢?你打开~/.profile看看就知道了,这货竟然在~/.profile文件里面source了~/.bashrc!
bash shell中的选项可控制shell的行为和功能,我们可以通过shopt命令来设置。使用set命令也可以,但它已被shopt替代,但为了向下兼容,set命令还是可以使用的。使用不带参数的shopt命令可以列出当前shell中只能由shopt设置的选项,用shopt -o可列出可由set命令设置的选项。
下面是一些可由set命令基本的选项,默认是关闭的。
进入emacs编辑模式vi
进入vi编辑模式ignoreeof
不允许单独使用Ctrl_D退出的用法,要使用exit。与IGNOREEOF=10等价noclobber
不允许重定向覆盖已存在文件noglob
不允许扩展文件名通配符nounset
使用未定义的变量时给出错误
下面是一些只能由shopt命令设置的选项。
自动改正cd命令参数中的小错误hostcomplete
以@开头时,按tab键可进行主机名的自动完成dotgblob
以点开始的文件名被包含在路径名扩展中mailwarn
显示邮件警告信息
shopt命令的选项如下:
显示可设置选项及当前取值-s
设置每一选项为on-u
设置每一选项为off-q
不输出信息-oShell变量有局部变量、环境变量之分。局部变量就是指在某个Shell中生效的变量,只在此次登录中有效。环境变量通常又称“全局变量”,虽然在Shell中变量默认就是全局的,但是为了让子Shall继承当前Shell的变量,需要使用export内建命令将其导出为环境变量。
一、Linux的变量种类
按变量的生存周期划分:
永久的:需要修改配置文件,变量永久生效。
临时的:使用export命令声明即可,变量在关闭shell时失效。
在配置永久的环境变量时,又可以按照作用范围分为
用户环境变量
系统环境变量。
系统环境变量对所有系统用户都有效,用户环境变量仅仅对当前的用户有效。
二、设置环境变量
直接运行export命令定义变量
& & & &在shell的命令行下直接使用[export 变量名=变量值] 定义变量。该变量只在当前的shell(BASH)或其子shell(BASH)下是有效的,shell关闭了,变量也就失效了,再打开新shell时就没有这个变量,需要使用的话还需要重新定义。
修改系统环境变量
系统环境变量一般保存在下面的文件中
/etc/profile
全局(公有)配置,不管是哪个用户,登录时都会读取该文件。
/etc/bash.bashrc
它也是全局(公有)的 bash执行时,不管是何种方式,都会读取此文件。
/etc/environment
不要轻易修改此文件
修改用户环境变量
用户环境变量通常被存储在下面的文件中:
~/.profile
若bash是以login方式执行时,读取~/.bash_profile,若它不存在,则读取~/.bash_login,若前两者不存在,读取~/.profile。
~/.bash_profile 或者~./bash_login
若bash是以login方式执行时,读取~/.bash_profile,若它不存,则读取~/.bash_login,若前两者不存在,读取 ~/.profile。
只有bash是以login形式执行时,才会读取.bash_profile,Unbutu默认没有此文件,可新建。 通常该配置文件还会配置成去读取~/.bashrc。
当bash是以non-login形式执行时,读取此文件。若是以login形式执行,则不会读取此文件。
~/.bash_profile是交互式、login 方式进入 bash 运行的
~/.bashrc 是交互式 non-login 方式进入 bash 运行的通常二者设置大致相同,所以通常前者会调用后者。
4. 修改环境变量配置文件
如想将一个路径加入到环境变量(例如$PATH)中,可以像下面这样做(修改/etc/profile):
sudo vi /etc/profile
以环境变量PATH为例子,环境变量的声明格式:
PATH=$PATH:PATH_1:PATH_2:PATH_3:------:PATH_N
export PATH
你可以自己加上指定的路径,中间用冒号隔开。环境变量更改后,在用户下次登陆时生效,如果想立刻生效,则可执行下面的语句:
$source /etc/profile
三、环境配置文件的区别
bashrc、.bash_profile、 .bashrc介绍
bash会在用户登录时,读取下列四个环境配置文件:
全局环境变量设置文件:/etc/profile、/etc/bashrc。
用户环境变量设置文件:~/.bash_profile、~/.bashrc。
读取顺序:① /etc/profile、② ~/.bash_profile、③ ~/.bashrc、④ /etc/bashrc。
① /etc/profile:此文件为系统的每个用户设置环境信息,系统中每个用户登录时都要执行这个脚本,如果系统管理员希望某个设置对所有用户都生效,可以写在这个脚本里,该文件也会从/etc/profile.d目录中的配置文件中搜集shell的设置。
② ~/.bash_profile:每个用户都可使用该文件设置专用于自己的shell信息,当用户登录时,该文件仅执行一次。默认情况下,他设置一些环境变量,执行用户的.bashrc文件。
③ ~/.bashrc:该文件包含专用于自己的shell信息,当登录时以及每次打开新shell时,该文件被读取。
④ /etc/bashrc:为每一个运行bash shell的用户执行此文件,当bash shell被打开时,该文件被读取。
2 .bashrc和.bash_profile的区别
& & & &.bash_profile会用在登陆shell, .bashrc 使用在交互式非登陆 shell 。简单说来,它们的区别主要是.bash_profile是在你每次登录的时候执行的;.bashrc是在你新开了一个命令行窗口时执行的。
& & & &当通过控制台进行登录(输入用户名和密码):在初始化命令行提示符的时候会执行.bash_profile 来配置你的shell环境。但是如果已经登录到机器,在Gnome或者是KDE也开了一个新的终端窗口(xterm),这时,.bashrc会在窗口命令行提示符出现前被执行。当你在终端敲入/bin/bash时.bashrc也会在这个新的bash实例启动的时候执行。
& & & &大多数的时候你不想维护两个独立的配置文件,一个登录的一个非登录的shell。当你设置PATH时,你想在两个文件都适用。可以在.bash_profile中调用.bashrc,然后将PATH和其他通用的设置放到.bashrc中。
& & & &要做到这几点,添加以下几行到.bash_profile中:
if [ -f ~/.bashrc ]; then
. ~/.bashrc
& & & &现在,当你从控制台登录机器的时候,.bashrc就会被执行。
四、常用的环境变量
BASH Bash Shell的全路径
CDPATH& & & &用于快速进入某个目录。
PATH& & & &决定了shell将到哪些目录中寻找命令或程序
HOME& & & &当前用户主目录
HISTSIZE& & & &历史记录数
LOGNAME& & & &当前用户的登录名
HOSTNAME& & & &指主机的名称
SHELL& & & &当前用户Shell类型
LANGUGE& & & &语言相关的环境变量,多语言可以修改此环境变量
MAIL& & & &当前用户的邮件存放目录
PS1& & & &基本提示符,对于root用户是#,对于普通用户是$
[1] /etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc
[2] Linux如何修改env看到的环境变量? .bashrc和.bash_profile区别
[3] linux环境变量,bashrc与bashprofile
本文已收录于以下专栏:
相关文章推荐
/etc/profile:此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行.并从/etc/profile.d目录的配置文件中搜集shell的设置.
英文描述为:
转:关于环境变量,profile ,bash_profile ,bashrc
程序员升职加薪指南!还缺一个“证”!
CSDN出品策划程序员9月规划,专为码农的升职加薪保驾护航,程序员的捷径,你get到了吗?听说阅读了这篇文章的人,都已实现了小梦想~快来揭秘!
/etc/profile:此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行.
并从/etc/profile.d目录的配置文件中搜集shell的设置.
/etc/bashrc:为...
QSplitter实现滑动伸缩窗口
这样可在多个UI界面上进行分部开发。避免都在一个UI下太凌乱……
在网上找了一些资料,很少有介绍这方面的,以及类似这样项目的源码。
看 一些基本控件的使用时,想到了一种方法:使用gridLayout控...
QTabWidget用法,笔记持续记录更新……
设置标签页头的名字:
ui-&tabWidget-&setTabText(0,&持卡人&);
ui-&tabWidget...
radioButton多选一,并获取当前选择的是哪一个radioButton。
QButtonGroup getThreeFucS
ui-&radioButton_doorTh...
QTableWidget 的用法实例,笔记持续记录更新……
初始化表的行、列、列头等属性:
ui-&tableWidget-...
/etc/profile是全局的,是私有的
/etc/profile用于整个系统所有用户, ~/.bash_profile, ~/.profile和~/.bashrc 用于各个用户,这里的&~&...
1 . .bash_profile
2 source .bash_profile
3 exec bash --login
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)Linux有问必答:如何在Linux中修改环境变量PATH
提问: 当我试着运行一个程序时,它提示&command not found&。 但这个程序就在/usr/local/bin下。我该如何添加/usr/local/bin到我的PATH变量下,这样我就可以不用指定路径来运行这个命令了。
在Linux中,PATH环境变量保存了一系列的目录用于用户在输入的时候搜索命令。PATH变量的值由一系列的由冒号分隔的绝对路径组成。每个用户都有特定的PATH环境变量(由系统级的PATH变量初始化)。
要检查用户的环境变量,用户模式下运行下面的命令:
$ echo $PATH
/usr/lib64/qt-3.3/bin:/bin:/usr/bin:/usr/sbin:/sbin:/home/xmodulo/bin
或者运行:
$ env | grep PATH
PATH=/usr/lib64/qt-3.3/bin:/bin:/usr/bin:/usr/sbin:/sbin:/home/xmodulo/bin
如果你的命令不存在于上面任何一个目录内,shell就会抛出一个错误信息:&command not found&。
如果你想要添加一个另外的目录(比如:/usr/local/bin)到你的PATH变量中,你可以用下面这些命令。
为特定用户修改PATH环境变量
如果你只想在当前的登录会话中临时地添加一个新的目录(比如:/usr/local/bin)给用户的默认搜索路径,你只需要输入下面的命令。
$ PATH=$PATH:/usr/local/bin
检查PATH是否已经更新:
$ echo $PATH
/usr/lib64/qt-3.3/bin:/bin:/usr/bin:/usr/sbin:/sbin:/home/xmodulo/bin:/usr/local/bin
更新后的PATH会在当前的会话一直有效。然而,更改将在新的会话中失效。
如果你想要永久更改PATH变量,用编辑器打开~/.bashrc (或者 ~/.bash_profile),接着在最后添加下面这行。
export PATH=$PATH:/usr/local/bin
接着运行下面这行永久激活更改:
$ source ~/.bashrc (或者 source ~/.bash_profile)
改变系统级的环境变量
如果你想要永久添加/usr/local/bin到系统级的PATH变量中,像下面这样编辑/etc/profile。
$ sudo vi /etc/profile
export PATH=$PATH:/usr/local/bin
你重新登录后,更新的环境变量就会生效了。
作者: 译者: 校对:
原创翻译, 荣誉推出
上一篇:下一篇:
12:20 的评论:
分隔每个路径是冒号,不是分号
抱歉抱歉, 是冒号,笔误——已经修正。
共计翻译: 522 篇
| 共计贡献: 1192 天
贡献时间: -&
分享到微信
打开微信,点击顶部的“╋”,
使用“扫一扫”将网页分享至微信。
请将我们加入您的广告过滤器的白名单,请支持开源站点。谢谢您。2005年12月 C/C++大版内专家分月排行榜第二2005年11月 C/C++大版内专家分月排行榜第二2005年8月 C/C++大版内专家分月排行榜第二
2009年9月 Linux/Unix社区大版内专家分月排行榜第三2005年9月 C/C++大版内专家分月排行榜第三
2011年5月 Linux/Unix社区大版内专家分月排行榜第一2011年4月 Linux/Unix社区大版内专家分月排行榜第一2011年3月 Linux/Unix社区大版内专家分月排行榜第一2010年12月 Linux/Unix社区大版内专家分月排行榜第一2010年11月 Linux/Unix社区大版内专家分月排行榜第一2010年10月 Linux/Unix社区大版内专家分月排行榜第一2010年9月 Linux/Unix社区大版内专家分月排行榜第一2010年8月 Linux/Unix社区大版内专家分月排行榜第一2010年7月 Linux/Unix社区大版内专家分月排行榜第一2010年6月 Linux/Unix社区大版内专家分月排行榜第一2010年5月 Linux/Unix社区大版内专家分月排行榜第一2010年4月 Linux/Unix社区大版内专家分月排行榜第一2010年3月 Linux/Unix社区大版内专家分月排行榜第一2010年2月 Linux/Unix社区大版内专家分月排行榜第一2010年1月 Linux/Unix社区大版内专家分月排行榜第一2009年10月 Linux/Unix社区大版内专家分月排行榜第一2009年9月 Linux/Unix社区大版内专家分月排行榜第一
2011年7月 Linux/Unix社区大版内专家分月排行榜第二2011年6月 Linux/Unix社区大版内专家分月排行榜第二2011年2月 Linux/Unix社区大版内专家分月排行榜第二
2009年4月 总版技术专家分月排行榜第一
2009年11月 Linux/Unix社区大版内专家分月排行榜第一2009年6月 Linux/Unix社区大版内专家分月排行榜第一2009年4月 C/C++大版内专家分月排行榜第一2009年3月 C/C++大版内专家分月排行榜第一2009年3月 Linux/Unix社区大版内专家分月排行榜第一2009年2月 Linux/Unix社区大版内专家分月排行榜第一
本帖子已过去太久远了,不再提供回复功能。Sample .bashrc
.bash_profile FilesAdvanced Bash-Scripting Guide: PrevNextAppendix M. Sample .bashrc
.bash_profile FilesThe ~/.bashrc file determines the
behavior of interactive shells. A good look at this file can
lead to a better understanding of Bash.Emmanuel
Rouat contributed the following very elaborate
.bashrc file, written for a Linux system.
He welcomes reader feedback on it.Study the file carefully, and feel free to reuse code
snippets and functions from it in your own
.bashrc file or even in your scripts.Example M-1. Sample .bashrc file# =============================================================== #
# PERSONAL $HOME/.bashrc FILE for bash-3.0 (or later)
# By Emmanuel Rouat [no-email]
# Last modified: Tue Nov 20 22:04:47 CET 2012
This file is normally read by interactive shells only.
#+ Here is the place to define your aliases, functions and
#+ other interactive features like your prompt.
The majority of the code here assumes you are on a GNU
#+ system (most likely a Linux box) and is often based on code
#+ found on Usenet or Internet.
See for instance:
http://tldp.org/LDP/abs/html/index.html
http://www.caliban.org/bash
/scripts/categories.html
http://www.dotfiles.org
The choice of colors was done for a shell with a dark background
#+ (white on black), and this is usually also suited for pure text-mode
#+ consoles (no X server available). If you use a white background,
#+ you'll have to do some other choices for readability.
This bashrc file is a bit overcrowded.
Remember, it is just just an example.
Tailor it to your needs.
# =============================================================== #
# --> Comments added by HOWTO author.
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
#-------------------------------------------------------------
# Source global definitions (if any)
#-------------------------------------------------------------
if [ -f /etc/bashrc ]; then
. /etc/bashrc
# --> Read /etc/bashrc, if present.
#--------------------------------------------------------------
Automatic setting of $DISPLAY (if not set already).
This works for me - your mileage may vary. . . .
The problem is that different types of terminals give
#+ different answers to 'who am i' (rxvt in particular can be
#+ troublesome) - however this code seems to work in a majority
#+ of cases.
#--------------------------------------------------------------
function get_xserver ()
case $TERM in
XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )
# Ane-Pieter Wieringa suggests the following alternative:
I_AM=$(who am i)
SERVER=${I_AM#*(}
SERVER=${SERVER%*)}
XSERVER=${XSERVER%%:*}
aterm | rxvt)
# Find some code that works here. ...
if [ -z ${DISPLAY:=""} ]; then
get_xserver
if [[ -z ${XSERVER}
|| ${XSERVER} == $(hostname) ||
${XSERVER} == "unix" ]]; then
DISPLAY=":0.0"
# Display on local host.
DISPLAY=${XSERVER}:0.0
# Display on remote host.
export DISPLAY
#-------------------------------------------------------------
# Some settings
#-------------------------------------------------------------
#set -o nounset
two options are useful for debugging.
#set -o xtrace
alias debug="set - set -o xtrace"
ulimit -S -c 0
# Don't want coredumps.
set -o notify
set -o noclobber
set -o ignoreeof
# Enable options:
shopt -s cdspell
shopt -s cdable_vars
shopt -s checkhash
shopt -s checkwinsize
shopt -s sourcepath
shopt -s no_empty_cmd_completion
shopt -s cmdhist
shopt -s histappend histreedit histverify
shopt -s extglob
# Necessary for programmable completion.
# Disable options:
shopt -u mailwarn
unset MAILCHECK
# Don't want my shell to warn me of incoming mail.
#-------------------------------------------------------------
# Greeting, motd etc. ...
#-------------------------------------------------------------
# Color definitions (taken from Color Bash Prompt HowTo).
# Some colors might look different of some terminals.
# For example, I see 'Bold Red' as 'orange' on my screen,
# hence the 'Green' 'BRed' 'Red' sequence I often use in my prompt.
# Normal Colors
Black='\e[0;30m'
Red='\e[0;31m'
Green='\e[0;32m'
Yellow='\e[0;33m'
Blue='\e[0;34m'
Purple='\e[0;35m'
Cyan='\e[0;36m'
White='\e[0;37m'
BBlack='\e[1;30m'
BRed='\e[1;31m'
BGreen='\e[1;32m'
BYellow='\e[1;33m'
BBlue='\e[1;34m'
BPurple='\e[1;35m'
BCyan='\e[1;36m'
BWhite='\e[1;37m'
# Background
On_Black='\e[40m'
On_Red='\e[41m'
On_Green='\e[42m'
On_Yellow='\e[43m'
On_Blue='\e[44m'
On_Purple='\e[45m'
On_Cyan='\e[46m'
On_White='\e[47m'
# Color Reset
ALERT=${BWhite}${On_Red} # Bold White on red background
echo -e "${BCyan}This is BASH ${BRed}${BASH_VERSION%.*}${BCyan}\
- DISPLAY on ${BRed}$DISPLAY${NC}\n"
if [ -x /usr/games/fortune ]; then
/usr/games/fortune -s
# Makes our day a bit more fun.... :-)
function _exit()
# Function to run upon exit of shell.
echo -e "${BRed}Hasta la vista, baby${NC}"
trap _exit EXIT
#-------------------------------------------------------------
# Shell Prompt - for many examples, see:
http://www.debian-administration.org/articles/205
/linux/bash-power-prompt.html
http://tldp.org/HOWTO/Bash-Prompt-HOWTO
/nojhan/liquidprompt
#-------------------------------------------------------------
# Current Format: [TIME USER@HOST PWD] >
== machine load is low
== machine load is medium
== machine load is high
== machine load is very high
== normal user
== SU to user
== local session
== secured remote connection (via ssh)
== unsecured remote connection
== more than 10% free disk space
== less than 10% free disk space
== less than 5% free disk space
== current user does not have write privileges
== current filesystem is size zero (like /proc)
== no background or suspended jobs in this shell
== at least one background job in this shell
== at least one suspended job in this shell
Command is added to the history file each time you hit enter,
so it's available to all shells (using 'history -a').
# Test connection type:
if [ -n "${SSH_CONNECTION}" ]; then
CNX=${Green}
# Connected on remote machine, via ssh (good).
elif [[ "${DISPLAY%%:0*}" != "" ]]; then
CNX=${ALERT}
# Connected on remote machine, not via ssh (bad).
CNX=${BCyan}
# Connected on local machine.
# Test user type:
if [[ ${USER} == "root" ]]; then
# User is root.
elif [[ ${USER} != $(logname) ]]; then
SU=${BRed}
# User is not login user.
SU=${BCyan}
# User is normal (well ... most of us are).
NCPU=$(grep -c 'processor' /proc/cpuinfo)
# Number of CPUs
SLOAD=$(( 100*${NCPU} ))
# Small load
MLOAD=$(( 200*${NCPU} ))
# Medium load
XLOAD=$(( 400*${NCPU} ))
# Xlarge load
# Returns system load as percentage, i.e., '40' rather than '0.40)'.
function load()
local SYSLOAD=$(cut -d " " -f1 /proc/loadavg | tr -d '.')
# System load of the current host.
echo $((10#$SYSLOAD))
# Convert to decimal.
# Returns a color indicating system load.
function load_color()
local SYSLOAD=$(load)
if [ ${SYSLOAD} -gt ${XLOAD} ]; then
echo -en ${ALERT}
elif [ ${SYSLOAD} -gt ${MLOAD} ]; then
echo -en ${Red}
elif [ ${SYSLOAD} -gt ${SLOAD} ]; then
echo -en ${BRed}
echo -en ${Green}
# Returns a color according to free disk space in $PWD.
function disk_color()
if [ ! -w "${PWD}" ] ; then
echo -en ${Red}
# No 'write' privilege in the current directory.
elif [ -s "${PWD}" ] ; then
local used=$(command df -P "$PWD" |
awk 'END {print $5} {sub(/%/,"")}')
if [ ${used} -gt 95 ]; then
echo -en ${ALERT}
# Disk almost full (>95%).
elif [ ${used} -gt 90 ]; then
echo -en ${BRed}
# Free disk space almost gone.
echo -en ${Green}
# Free disk space is ok.
echo -en ${Cyan}
# Current directory is size '0' (like /proc, /sys etc).
# Returns a color according to running/suspended jobs.
function job_color()
if [ $(jobs -s | wc -l) -gt "0" ]; then
echo -en ${BRed}
elif [ $(jobs -r | wc -l) -gt "0" ] ; then
echo -en ${BCyan}
# Adds some text in the terminal frame (if applicable).
# Now we construct the prompt.
PROMPT_COMMAND="history -a"
case ${TERM} in
*term | rxvt | linux)
PS1="\[\$(load_color)\][\A\[${NC}\] "
# Time of day (with load info):
PS1="\[\$(load_color)\][\A\[${NC}\] "
# User@Host (with connection type info):
PS1=${PS1}"\[${SU}\]\u\[${NC}\]@\[${CNX}\]\h\[${NC}\] "
# PWD (with 'disk space' info):
PS1=${PS1}"\[\$(disk_color)\]\W]\[${NC}\] "
# Prompt (with 'job' info):
PS1=${PS1}"\[\$(job_color)\]>\[${NC}\] "
# Set title of current xterm:
PS1=${PS1}"\[\e]0;[\u@\h] \w\a\]"
PS1="(\A \u@\h \W) > " # --> PS1="(\A \u@\h \w) > "
# --> Shows full pathname of current dir.
export TIMEFORMAT=$'\nreal %3R\tuser %3U\tsys %3S\tpcpu %P\n'
export HISTIGNORE="&:bg:fg:ll:h"
export HISTTIMEFORMAT="$(echo -e ${BCyan})[%d/%m %H:%M:%S]$(echo -e ${NC}) "
export HISTCONTROL=ignoredups
export HOSTFILE=$HOME/.hosts
# Put a list of remote hosts in ~/.hosts
#============================================================
ALIASES AND FUNCTIONS
Arguably, some functions defined here are quite big.
If you want to make this file smaller, these functions can
#+ be converted into scripts and removed from here.
#============================================================
#-------------------
# Personnal Aliases
#-------------------
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# -> Prevents accidentally clobbering files.
alias mkdir='mkdir -p'
alias h='history'
alias j='jobs -l'
alias which='type -a'
alias ..='cd ..'
# Pretty-print of some PATH variables:
alias path='echo -e ${PATH//:/\\n}'
alias libpath='echo -e ${LD_LIBRARY_PATH//:/\\n}'
alias du='du -kh'
# Makes a more readable output.
alias df='df -kTh'
#-------------------------------------------------------------
# The 'ls' family (this assumes you use a recent GNU ls).
#-------------------------------------------------------------
# Add colors for filetype and
human-readable sizes by default on 'ls':
alias ls='ls -h --color'
alias lx='ls -lXB'
Sort by extension.
alias lk='ls -lSr'
Sort by size, biggest last.
alias lt='ls -ltr'
Sort by date, most recent last.
alias lc='ls -ltcr'
Sort by/show change time,most recent last.
alias lu='ls -ltur'
Sort by/show access time,most recent last.
# The ubiquitous 'll': directories first, with alphanumeric sorting:
alias ll="ls -lv --group-directories-first"
alias lm='ll |more'
Pipe through 'more'
alias lr='ll -R'
Recursive ls.
alias la='ll -A'
Show hidden files.
alias tree='tree -Csuh'
Nice alternative to 'recursive ls' ...
#-------------------------------------------------------------
# Tailoring 'less'
#-------------------------------------------------------------
alias more='less'
export PAGER=less
export LESSCHARSET='latin1'
export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-'
# Use this if lesspipe.sh exists.
export LESS='-i -N -w
-z-4 -g -e -M -X -F -R -P%t?f%f \
:stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...'
# LESS man page colors (makes Man pages more readable).
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'
#-------------------------------------------------------------
# Spelling typos - highly personnal and keyboard-dependent :-)
#-------------------------------------------------------------
alias xs='cd'
alias vf='cd'
alias moer='more'
alias moew='more'
alias kk='ll'
#-------------------------------------------------------------
# A few fun ones
#-------------------------------------------------------------
# Adds some text in the terminal frame (if applicable).
function xtitle()
case "$TERM" in
*term* | rxvt)
"\e]0;$*\a" ;;
# Aliases that use xtitle
alias top='xtitle Processes on $HOST && top'
alias make='xtitle Making $(basename $PWD) ; make'
# .. and functions
function man()
xtitle The $(basename $1|tr -d .[:digit:]) manual
command man -a "$i"
#-------------------------------------------------------------
# Make the following commands run in background automatically:
#-------------------------------------------------------------
function te()
# wrapper around xemacs/gnuserv
if [ "$(gnuclient -batch -eval t 2>&-)" == "t" ]; then
gnuclient -q "$@";
( xemacs "$@" &);
function soffice() { command soffice "$@" & }
function firefox() { command firefox "$@" & }
function xpdf() { command xpdf "$@" & }
#-------------------------------------------------------------
# File & strings related functions:
#-------------------------------------------------------------
# Find a file with a pattern in name:
function ff() { find . -type f -iname '*'"$*"'*' - }
# Find a file with pattern $1 in name and Execute $2 on it:
function fe() { find . -type f -iname '*'"${1:-}"'*' \
-exec ${2:-file} {} \; }
Find a pattern in a set of files and highlight them:
#+ (needs a recent version of egrep).
function fstr()
local mycase=""
local usage="fstr: find string in files.
Usage: fstr [-i] \"pattern\" [\"filename pattern\"] "
while getopts :it opt
case "$opt" in
i) mycase="-i " ;;
*) echo "$usage";;
shift $(( $OPTIND - 1 ))
if [ "$#" -lt 1 ]; then
echo "$usage"
find . -type f -name "${2:-*}" -print0 | \
xargs -0 egrep --color=always -sn ${case} "$1" 2>&- | more
function swap()
{ # Swap 2 filenames around, if they exist (from Uzi's bashrc).
local TMPFILE=tmp.$$
[ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1
[ ! -e $1 ] && echo "swap: $1 does not exist" && return 1
[ ! -e $2 ] && echo "swap: $2 does not exist" && return 1
mv "$1" $TMPFILE
mv "$2" "$1"
mv $TMPFILE "$2"
function extract()
# Handy Extract Program
if [ -f $1 ] ; then
case $1 in
*.tar.bz2)
tar xvjf $1;
tar xvzf $1;
bunzip2 $1;
unrar x $1;
gunzip $1;
tar xvf $1;
tar xvjf $1;
tar xvzf $1;
uncompress $1;
echo "'$1' cannot be extracted via >extract<" ;;
echo "'$1' is not a valid file!"
# Creates an archive (*.tar.gz) from given directory.
function maketar() { tar cvzf "${1%%/}.tar.gz"
"${1%%/}/"; }
# Create a ZIP archive of a file or folder.
function makezip() { zip -r "${1%%/}.zip" "$1" ; }
# Make your directories and files access rights sane.
function sanitize() { chmod -R u=rwX,g=rX,o= "$@" ;}
#-------------------------------------------------------------
# Process/system related functions:
#-------------------------------------------------------------
function my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,bsdtime, }
function pp() { my_ps f | awk '!/awk/ && $0~var' var=${1:-".*"} ; }
function killps()
# kill by process name
local pid pname sig="-TERM"
# default signal
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
echo "Usage: killps [-SIGNAL] pattern"
if [ $# = 2 ]; then sig=$1 ; fi
for pid in $(my_ps| awk '!/awk/ && $0~pat { print $1 }' pat=${!#} )
pname=$(my_ps | awk '$1~var { print $5 }' var=$pid )
if ask "Kill process $pid <$pname> with signal $sig?"
then kill $sig $pid
function mydf()
# Pretty-print of 'df' output.
# Inspired by 'dfc' utility.
if [ ! -d $fs ]
echo -e $fs" :No such file or directory" ; continue
local info=( $(command df -P $fs | awk 'END{ print $2,$3,$5 }') )
local free=( $(command df -Pkh $fs | awk 'END{ print $4 }') )
local nbstars=$(( 20 * ${info[1]} / ${info[0]} ))
local out="["
for ((j=0;j<20;j++)); do
if [ ${j} -lt ${nbstars} ]; then
out=$out"*"
out=$out"-"
out=${info[2]}" "$out"] ("$free" free on "$fs")"
echo -e $out
function my_ip() # Get IP adress on ethernet.
MY_IP=$(/sbin/ifconfig eth0 | awk '/inet/ { print $2 } ' |
sed -e s/addr://)
echo ${MY_IP:-"Not connected"}
function ii()
# Get current host related info.
echo -e "\nYou are logged on ${BRed}$HOST"
echo -e "\n${BRed}Additionnal information:$NC " ; uname -a
echo -e "\n${BRed}Users logged on:$NC " ; w -hs |
cut -d " " -f1 | sort | uniq
echo -e "\n${BRed}Current date :$NC " ; date
echo -e "\n${BRed}Machine stats :$NC " ; uptime
echo -e "\n${BRed}Memory stats :$NC " ; free
echo -e "\n${BRed}Diskspace :$NC " ; mydf / $HOME
echo -e "\n${BRed}Local IP Address :$NC" ; my_ip
echo -e "\n${BRed}Open connections :$NC "; netstat -pan --
#-------------------------------------------------------------
# Misc utilities:
#-------------------------------------------------------------
function repeat()
# Repeat n times command.
local i max
for ((i=1; i <= i++)); do
# --> C-like syntax
eval "$@";
function ask()
# See 'killps' for example of use.
echo -n "$@" '[y/n] ' ; read ans
case "$ans" in
y*|Y*) return 0 ;;
*) return 1 ;;
function corename()
# Get name of app that created a corefile.
echo -n $file : ; gdb --core=$file --batch | head -1
#=========================================================================
PROGRAMMABLE COMPLETION SECTION
Most are taken from the bash 2.05 documentation and from Ian McDonald's
# 'Bash completion' package (http://www.caliban.org/bash/#completion)
You will in fact need bash more recent then 3.0 for some features.
Note that most linux distributions now provide many completions
# 'out of the box' - however, you might need to make your own one day,
so I kept those here as examples.
#=========================================================================
if [ "${BASH_VERSION%.*}" \< "3.0" ]; then
echo "You will need to upgrade to version 3.0 for full \
programmable completion features"
shopt -s extglob
# Necessary.
complete -A hostname
rsh rcp telnet rlogin ftp ping disk
complete -A export
complete -A variable
export local readonly unset
complete -A enabled
complete -A alias
alias unalias
complete -A function
complete -A user
su mail finger
complete -A helptopic
# Currently same as builtins.
complete -A shopt
complete -A stopped -P '%' bg
complete -A job -P '%'
fg jobs disown
complete -A directory
mkdir rmdir
complete -A directory
-o default cd
# Compression
complete -f -o default -X '*.+(zip|ZIP)'
complete -f -o default -X '!*.+(zip|ZIP)' unzip
complete -f -o default -X '*.+(z|Z)'
complete -f -o default -X '!*.+(z|Z)'
uncompress
complete -f -o default -X '*.+(gz|GZ)'
complete -f -o default -X '!*.+(gz|GZ)'
complete -f -o default -X '*.+(bz2|BZ2)'
complete -f -o default -X '!*.+(bz2|BZ2)' bunzip2
complete -f -o default -X '!*.+(zip|ZIP|z|Z|gz|GZ|bz2|BZ2)' extract
# Documents - Postscript,pdf,dvi.....
complete -f -o default -X '!*.+(ps|PS)'
gs ghostview ps2pdf ps2ascii
complete -f -o default -X \
'!*.+(dvi|DVI)' dvips dvipdf xdvi dviselect dvitype
complete -f -o default -X '!*.+(pdf|PDF)' acroread pdf2ps
complete -f -o default -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?\
(.gz|.GZ|.bz2|.BZ2|.Z))' gv ggv
complete -f -o default -X '!*.texi*' makeinfo texi2dvi texi2html texi2pdf
complete -f -o default -X '!*.tex' tex latex slitex
complete -f -o default -X '!*.lyx' lyx
complete -f -o default -X '!*.+(htm*|HTM*)' lynx html2ps
complete -f -o default -X \
'!*.+(doc|DOC|xls|XLS|ppt|PPT|sx?|SX?|csv|CSV|od?|OD?|ott|OTT)' soffice
# Multimedia
complete -f -o default -X \
'!*.+(gif|GIF|jp*g|JP*G|bmp|BMP|xpm|XPM|png|PNG)' xv gimp ee gqview
complete -f -o default -X '!*.+(mp3|MP3)' mpg123 mpg321
complete -f -o default -X '!*.+(ogg|OGG)' ogg123
complete -f -o default -X \
'!*.@(mp[23]|MP[23]|ogg|OGG|wav|WAV|pls|\
m3u|xm|mod|s[3t]m|it|mtm|ult|flac)' xmms
complete -f -o default -X '!*.@(mp?(e)g|MP?(E)G|wma|avi|AVI|\
asf|vob|VOB|bin|dat|vcd|ps|pes|fli|viv|rm|ram|yuv|mov|MOV|qt|\
QT|wmv|mp3|MP3|ogg|OGG|ogm|OGM|mp4|MP4|wav|WAV|asx|ASX)' xine
complete -f -o default -X '!*.pl'
perl perl5
This is a 'universal' completion function - it works when commands have
#+ a so-called 'long options' mode , ie: 'ls --all' instead of 'ls -a'
Needs the '-o' option of grep
#+ (try the commented-out version if not available).
First, remove '=' from completion word separators
#+ (this will allow completions like 'ls --color=auto' to work correctly).
COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}
_get_longopts()
#$1 --help | sed
-e '/--/!d' -e 's/.*--\([^[:space:].,]*\).*/--\1/'| \
#grep ^"$2" |sort -
$1 --help | grep -o -e "--[^[:space:].,]*" | grep -e "$2" |sort -u
_longopts()
cur=${COMP_WORDS[COMP_CWORD]}
case "${cur:-*}" in
case "$1" in
eval cmd="$1" ;;
cmd="$1" ;;
COMPREPLY=( $(_get_longopts ${1} ${cur} ) )
-o default -F _longopts configure bash
-o default -F _longopts wget id info a2ps ls recode
local cur ext regex tar untar
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
# If we want an option, return the possible long options.
case "$cur" in
COMPREPLY=( $(_get_longopts $1 $cur ) ); return 0;;
if [ $COMP_CWORD -eq 1 ]; then
COMPREPLY=( $( compgen -W 'c t x u r d A' -- $cur ) )
case "${COMP_WORDS[1]}" in
COMPREPLY=( $( compgen -f $cur ) )
+([^Izjy])f)
regex=$ext
ext='tar.gz'
regex='t\(ar\.\)\(gz\|Z\)'
ext='t?(ar.)bz?(2)'
regex='t\(ar\.\)bz2\?'
COMPREPLY=( $( compgen -f $cur ) )
if [[ "$COMP_LINE" == tar*.$ext' '* ]]; then
# Complete on files in tar file.
# Get name of tar file from command line.
tar=$( echo "$COMP_LINE" | \
sed -e 's|^.* \([^ ]*'$regex'\) .*$|\1|' )
# Devise how to untar and list it.
untar=t${COMP_WORDS[1]//[^Izjyf]/}
COMPREPLY=( $( compgen -W "$( echo $( tar $untar $tar \
2>/dev/null ) )" -- "$cur" ) )
# File completion on relevant files.
COMPREPLY=( $( compgen -G $cur\*.$ext ) )
complete -F _tar -o default tar
local mdef makef makef_dir="." makef_
COMPREPLY=();
cur=${COMP_WORDS[COMP_CWORD]};
prev=${COMP_WORDS[COMP_CWORD-1]};
case "$prev" in
COMPREPLY=($(compgen -f $cur ));
case "$cur" in
COMPREPLY=($(_get_longopts $1 $cur ));
# ... make reads
GNUmakefile,
then makefile
then Makefile ...
if [ -f ${makef_dir}/GNUmakefile ]; then
makef=${makef_dir}/GNUmakefile
elif [ -f ${makef_dir}/makefile ]; then
makef=${makef_dir}/makefile
elif [ -f ${makef_dir}/Makefile ]; then
makef=${makef_dir}/Makefile
makef=${makef_dir}/*.mk
# Local convention.
Before we scan for targets, see if a Makefile name was
#+ specified with -f.
for (( i=0; i < ${#COMP_WORDS[@]}; i++ )); do
if [[ ${COMP_WORDS[i]} == -f ]]; then
# eval for tilde expansion
eval makef=${COMP_WORDS[i+1]}
[ ! -f $makef ] && return 0
# Deal with included Makefiles.
makef_inc=$( grep -E '^-?include' $makef |
sed -e "s,^.* ,"$makef_dir"/," )
for file in $makef_ do
[ -f $file ] && makef="$makef $file"
If we have a partial word to complete, restrict completions
#+ to matches of that word.
if [ -n "$cur" ]; then gcmd='grep "^$cur"' ; else gcmd= fi
COMPREPLY=( $( awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ \
{split($1,A,/ /);for(i in A)print A[i]}' \
$makef 2>/dev/null | eval $gcmd
complete -F _make -X '+($*|*.[cho])' make gmake pmake
_killall()
local cur prev
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
Get a list of processes
#+ (the first sed evaluation
#+ takes care of swapped out processes, the second
#+ takes care of getting the basename of the process).
COMPREPLY=( $( ps -u $USER -o comm
sed -e '1,1d' -e 's#[]\[]##g' -e 's#^.*/##'| \
awk '{if ($0 ~ /^'$cur'/) print $0}' ))
complete -F _killall killall killps
# Local Variables:
# mode:shell-script
# sh-shell:bash
# End:And, here is a snippet from Andrzej Szelachowski's instructive
.bash_profile file.Example M-2. .bash_profile file# From Andrzej Szelachowski's ~/.bash_profile:
Note that a variable may require special treatment
#+ if it will be exported.
DARKGRAY='\e[1;30m'
LIGHTRED='\e[1;31m'
GREEN='\e[32m'
YELLOW='\e[1;33m'
LIGHTBLUE='\e[1;34m'
PCT="\`if [[ \$EUID -eq 0 ]]; then T='$LIGHTRED' ; else T='$LIGHTBLUE';
echo \$T \`"
For "literal" command substitution to be assigned to a variable,
#+ use escapes and double quotes:
PCT="\` ... \`" . . .
Otherwise, the value of PCT variable is assigned only once,
#+ when the variable is exported/read from .bash_profile,
#+ and it will not change afterwards even if the user ID changes.
PS1="\n$GREEN[\w] \n$DARKGRAY($PCT\t$DARKGRAY)-($PCT\u$DARKGRAY)-($PCT\!
$DARKGRAY)$YELLOW-> $NC"
Escape a variables whose value changes:
if [[ \$EUID -eq 0 ]],
Otherwise the value of the EUID variable will be assigned only once,
#+ as above.
When a variable is assigned, it should be called escaped:
Otherwise the value of the T variable is taken from the moment the PCT
#+ variable is exported/read from .bash_profile.
So, in this example it would be null.
When a variable's value contains a semicolon it should be strong quoted:
T='$LIGHTRED',
Otherwise, the semicolon will be interpreted as a command separator.
Variables PCT and PS1 can be merged into a new PS1 variable:
PS1="\`if [[ \$EUID -eq 0 ]]; then PCT='$LIGHTRED';
else PCT='$LIGHTBLUE';
echo '\n$GREEN[\w] \n$DARKGRAY('\$PCT'\t$DARKGRAY)-\
('\$PCT'\u$DARKGRAY)-('\$PCT'\!$DARKGRAY)$YELLOW-> $NC'\`"
# The trick is to use strong quoting for parts of old PS1 variable.PrevHomeNextHistory Commands&Converting DOS Batch Files to Shell Scripts}

我要回帖

更多关于 linux 添加定时任务 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信