Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19733397
  • 博文数量: 679
  • 博客积分: 10495
  • 博客等级: 上将
  • 技术积分: 9308
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-18 10:51
文章分类

全部博文(679)

文章存档

2012年(5)

2011年(38)

2010年(86)

2009年(145)

2008年(170)

2007年(165)

2006年(89)

分类:

2008-10-21 18:39:40

Linux shell - 环境和shell变量

磁针石

联系方式: gmail and gtalk: xurongzhong#gmail.com

文件路径:    D:\blog\@Linux\shell

 

参考资料

LINUXUNIX SHELL编程指南》之 “第14章环境和shell变量”

《学习bash shell 3版》Chapter 3. Customizing Your Environment

2008-10-21 建立初稿。LINUXUNIX SHELL编程指南》个别例子还没有涉及。环境变量和本地变量不必去刻意区分,因为很多时候也有混用。

简介

 

为使shell编程更有效,系统提供了一些shell变量。shell变量可以保存诸如路径名、文件名或者一个数字这样的变量名。shell将其中任何设置都看做文本字符串。

有两种变量,本地和环境。严格地说可以有4种,但其余两种是只读的,可以认为是特殊变量,它用于向shell脚本传递参数。

本章内容有:
• shell
变量。
环境变量。
变量替换。
导出变量。
特定变量。
向脚本传递信息。
在系统命令行下使用位置参数。

本地变量

 

变量设置时的不同模式

Variable-name =value 设置实际值到Variable-name

Variable-name +value 如果设置了Variable-name,则重设其值

Variable-name:?value 如果未设置Variable-name,显示未定义用户错误信息

Variable-name ?value 如果未设置Variable-name,显示系统错误信息

Variable-name:= value 如果未设置Variable-name e,设置其值

Variable-name :- value 同上,但是取值并不设置到Variable-name,可以被替换

注意,等号两边可以有空格。如果取值包含空格,必须用引号括起来。shell变量可以用大小写字母。

变量的设定,显示和清除

]# HELLO='Hello World!'

]# echo $HELLO

Hello World!

]# echo ${HELLO};

Hello World!

 

使用set命令显示所有本地定义的shell变量。使用unset命令清除变量。

 

设置只读变量:

]# HELLO='Hello World!'

]# readonly HELLO

]# HELLO="YES"

-bash: HELLO: readonly variable

环境变量

环境变量用于所有用户进程(经常称为子进程),不像本地变量(只用于现在的shell)环境变量可用于所有子进程,这包括编辑器、脚本和应用。

环境变量可以在命令行中设置,但用户注销时这些值将丢失,因此最好在profile文件中定义。系统管理员可能在/etc/profile文件中已经设置了一些环境变量。将之放入profile文件意味着每次登录时这些值都将被初始化。

环境变量应用于用户进程前,必须用export命令导出。

使用env命令可以查看所有的环境变量。

比如:

PATH=$PATH:$HOME/bin:/usr/local/ActiveTcl/bin:/home/meil/program/expect

export PATH

使用unset命令清除变量。

 

Brourne shell 有一些预留的环境变量名,这些变量名不能用作其他用途。通常在/etc/profile中建立这些嵌入的环境变量,但也不完全是,这取决于用户自己。以下是嵌入shell变量列表。

CDPATH:改变目录路径变量,保留一系列由冒号隔开的路径名,用于cd命令
EXINIT:EXINIT
变量保存使用vi编辑器时的初始化选项。
HOME:
通常定位于passwd文件的倒数第2列,用于保存用户自身文件。
IFS:
用作shell指定的缺省域分隔符。
LOGNAME:
MAIL
MAILCHECK
MAILPATH
PATH
PS1:
基本提示符包含shell提示符,缺省对超级用户为#,其他为$。可以使用任何符号作提示符
PS2:PS2
为附属提示符,缺省为符号> PS2用于执行多行命令或超过一行的一个命令。
SHELL
TERMINFO:
终端初始化变量保存终端配置文件的位置。通常在/usr/lib/terminfo/usr/share/terminfo/
TERM:
保存终端类型。设置TERM使应用获知终端对屏幕和键盘响应的控制序列类型,常用的有vt100,vt200vt200-8等。
TZ

其他环境变量:

EDITOR

PWD

PAGER

MAMPATH

LPDESTPRINTER

 

$ H O M E. profile文件中设置环境变量时,还有另一种方法导出这些变量。使用s e t命令- a选项,即set -a指明所有变量直接被导出。不要在/etc/profile中使用这种方法,最好只在自己的$ H O M E. profile文件中使用。

环境变量可以在不同的程序中传递参数.

位置变量参数:
本章开始提到有4种变量,本地、环境,还有两种变量被认为是特殊变量,因为它们是只读的。这两种变量即为位置变量和特定变量参数。
参数相关数目传入脚本,此数目可以任意多,但只有前9个可以被访问,使用shift命令可以改变这个限制。


14-2 特定shell变量
$#
传递到脚本的参数个数
$*
以一个单字符串显示所有向脚本传递的参数。与位置变量不同,此选项参数可超过9
$$
脚本运行的当前进程I D
$!
后台运行的最后一个进程的进程I D
$@
$#相同,但是使用时加引号,并在引号中返回每个参数
$-
显示shell使用的当前选项,与set命令功能相同
$?
显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。

 

位置变量

本章开始提到有4种变量,本地、环境,还有两种变量被认为是特殊变量,因为它们是只读的。这两种变量即为位置变量和特定变量参数。

位置变量参数相关数目传入脚本,此数目可以任意多,但只有前9个可以被访问,使用shift命令可以改变这个限制。有$0-$9, $ 0返回当前目录路径。

特定变量参数如下:
$#
传递到脚本的参数个数
$*
以一个单字符串显示所有向脚本传递的参数。与位置变量不同,此选项参数可超过9
$$
脚本运行的当前进程id
$!
后台运行的最后一个进程的进程id
$@
$#相同,但是使用时加引号,并在引号中返回每个参数
$-
显示shell使用的当前选项,与set命令功能相同
$?
显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。

 

 

§3     环境自定义

§3.1  .bash_profile, .bash_logout, and .bashrc

修改了.bash_profile之后,要使用source .bash_profile才能生效,.source一样的效果。如果.bash_profile不存在,寻找.bash_login,其次是.profile。分别和c shell Bourne shell类似。

.bashrc则在启动子shell的时候使用,.bash_profile是作为登陆shell时使用。.bash_logout则在退出登陆shell时使用。

§3.2  别名

 

alias rm='rm -i'

alias cp='cp -i'

alias mv='mv -i'

 

       不像c shellbash中别名不支持变量。=前后不能又空格。

alias cdvoy='cd sipp/demo/animation/voyager'

shell脚本和函数实际可以取代别名。

 

§3.3  选项

       -表示打开,+表示关闭。

       基本参数如下:

Option

Description

emacs

Enters emacs editing mode (on by default)

ignoreeof

Doesn't allow use of a single CTRL-D to log off; use the exit command to log off immediately (this has the same effect as setting the shell variable IGNOREEOF=10)

noclobber

Doesn't allow output redirection (>) to overwrite an existing file

noglob

Doesn't expand filename wildcards like * and ? (wildcard expansion is sometimes called globbing)

nounset

Indicates an error when trying to use a variable that is undefined

vi

Enters vi editing mode

 

附录B列出了所有参数。set –o可以看出他们的状态。

 

shopt

Option

Meaning

-p

Displays a list of the settable options and their current values

-s

Sets each option name

-u

Unsets each option name

-q

Suppresses normal output; the return status indicates if a variable is set or unset

-o

Allows the values of the option names to be those defined for the -o option of the set command

 

Option

Meaning

cdable_vars

If set, an argument to the cd built-in command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.

checkhash

If set, bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed.

cmdhist

If set, bash attempts to save all lines of a multiple-line command in the same history entry.

dotglob

If set, bash includes filenames beginning with a . (dot) in the results of pathname expansion.

execfail

If set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the exec command. An interactive shell does not exit if exec fails.

histappend

If set, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.

lithist

If set, and the cmdhist option is enabled, multiline commands are saved to the history with embedded newlines, rather than using semicolon separators where possible.

mailwarn

If set, and a file that bash is checking for mail has been accessed since the last time it was checked, the message "The mail in mailfile has been read" is displayed.

 

 

§3.4  shell 变量

*变量和引用

双引号的作用:

 

fred='Four spaces between these    words.'

# echo "$fred"

Four spaces between these    words.

# echo $fred 

Four spaces between these words.

如果不加双引号,shell会把输出做类似shell命令的处理,多个空格被缩成一个。

 

*内置变量

 

-*编辑模式变量

 

 

Table 3-4. Editing mode variables

Variable

Meaning

HISTCMD

The history number of the current command.

HISTCONTROL

A list of patterns, separated by colons (:), which can have the following values. ignorespace: lines beginning with a space are not entered into the history list. ignoredups: lines matching the last history line are not entered. erasedups: all previous lines matching the current line are removed from the history list before the line is saved. ignoreboth: enables both ignorespace and ignoredups.[8]

HISTIGNORE

A list of patterns, separated by colons (:), used to decide which command lines to save in the history list. Patterns are considered to start at the beginning of the command line and must fully specify the line, i.e., no wildcard (*) is implicitly appended. The patterns are checked against the line after HISTCONTROL is applied. An ampersand (&) matches the previous line. An explicit & may be generated by escaping it with a backslash.[9]

HISTFILE

Name of history file in which the command history is saved. The default is ~/.bash_history.

HISTFILESIZE

The maximum number of lines to store in the history file. The default is 500. When this variable is assigned a value, the history file is truncated, if necessary, to the given number of lines.

HISTSIZE

The maximum number of commands to remember in the command history. The default is 500.

HISTTIMEFORMAT

If it is set and not null, its value is used as a format string for strftime(3) to print the time stamp associated with each history entry displayed by the history command. Time stamps are written to the history file so they may be preserved across shell sessions.[10]

FCEDIT

Pathname of the editor to use with the fc command.

 

 

HISTSIZE针对内存中的命令历史

HISTCONTROLignoredups选项可以去掉重复命令。

HISTIGNORE表示可以忽略的部分,添加&还可以避免重复。比如:l*:&

HISTTIMEFORMAT可以设定时间戳,比如:HISTTIMEFORMAT="%y/%m/%d %T "参数如下。

 

Table 3-5. Time stamp formats

Format

Replaced by

%a

The locale's abbreviated weekday name

%A

The locale's full weekday name

%b

The locale's abbreviated month name

%B

The locale's full month name

%c

The locale's appropriate date and time representation

%C

The century number (the year divided by 100 and truncated to an integer) as a decimal number [00-99]

%d

The day of the month as a decimal number [01-31]

%D

The date in American format; the same value as %m/%d/%y.

%e

The day of the month as a decimal number [1-31]; a single digit is preceded by a space

%h

The same as %b

%H

The hour (24-hour clock) as a decimal number [00-23]

%I

The hour (12-hour clock) as a decimal number [01-12]

%j

The day of the year as a decimal number [001-366]

%m

The month as a decimal number [01-12]

%M

The minute as a decimal number [00-59]

%n

A newline character

%p

The locale's equivalent of either a.m. or p.m

%r

The time in a.m. and p.m. notation; in the POSIX locale this is equivalent to %I:%M:%S %p

%R

The time in 24-hour notation (%H:%M)

%S

The second as a decimal number [00-61]

%t

A tab character

%T

The time (%H:%M:%S)

%u

The weekday as a decimal number [1-7], with 1 representing Monday

%U

The week number of the year (Sunday as the first day of the week) as a decimal number [00-53]

%V

The week number of the year (Monday as the first day of the week) as a decimal number [01-53]; if the week containing 1 January has four or more days in the new year, then it is considered week 1—otherwise, it is the last week of the previous year, and the next week is week 1

%w

The weekday as a decimal number [0-6], with 0 representing Sunday

%W

The week number of the year (Monday as the first day of the week) as a decimal number [00-53]; all days in a new year preceding the first Monday are considered to be in week 0

%x

The locale's appropriate date representation

%X

The locale's appropriate time representation

%y

The year without century as a decimal number [00-99]

%Y

The year with century as a decimal number

%Z

The timezone name or abbreviation, or by nothing if no timezone information exists

%%

%

 

Shell通过检查文件是否更新来判断是否有邮件。bash只能在邮件到达时提示"you have new mail"BSD中的biff可以在任何时候提示。

 

-*邮件变量

 

Table 3-6. Mail variables

Variable

Meaning

MAIL

Name of file to check for incoming mail

MAILCHECK

How often, in seconds, to check for new mail (default 60 seconds)

MAILPATH

List of filenames, separated by colons (:), to check for incoming mail

一些用户使用非标准的mailers,使用多个mail文件,MAILPATH用于适应这种情况,bash会检查MAILPATH中的每个文件。

比如:MAILPATH=/usr/mail/you/martin:/usr/mail/you/geoffm:\

/usr/mail/you/paulr。更复杂的例子暂略。

 

-*提示符变量

 

Shell4个提示符:PS1, PS2, PS3, and PS4PS1为基本提示字符串。默认值是"\s-\v\$ ".

比如PS1="\u--> ",添加用户名显示。PS1="\u \!--> "的显示结果如下:alice 1—>, alice 2—>等。PS1="\w--> "显示工作路径.

 

Table 3-7. Prompt string customizations

Command

Meaning

\a

The ASCII bell character (007)

\A

The current time in 24-hour HH:MM format

\d

The date in "Weekday Month Day" format

\D {format}

The format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation; the braces are required

\e

The ASCII escape character (033)

\H

The hostname

\h

The hostname up to the first "."

\j

The number of jobs currently managed by the shell

\l

The basename of the shell's terminal device name

\n

A carriage return and line feed

\r

A carriage return

\s

The name of the shell

\T

The current time in 12-hour HH:MM:SS format

\t

The current time in HH:MM:SS format

\@

The current time in 12-hour a.m./p.m. format

\u

The username of the current user

\v

The version of bash (e.g., 2.00)

\V

The release of bash; the version and patchlevel (e.g., 2.00.0)

\w

The current working directory

\W

The basename of the current working directory

\#

The command number of the current command

\!

The history number of the current command

\$

If the effective UID is 0, print a #, otherwise print a $

\nnn

Character code in octal

\\

Print a backslash

\[

Begin a sequence of non-printing characters, such as terminal control sequences

\]

End a sequence of non-printing characters

PS2为第2提示符,一般用于续行提示。PS3 and PS4用户shell程序设计和调测,见第59章。

 

-PATH

-*命令哈希

输入命令的时候先查找hash,而后才是PATH.

比如:

#hash

hits    command

   1    /bin/grep

   1    /bin/chmod

   1    /usr/bin/vim

   5    /usr/bin/ssh

   1    /bin/ls

 

-*目录查找路径和变量

先查找当前路径,然后CDPATH

# pwd

/root/temp

[root@localhost temp]# CDPATH=/usr/local/rss

[root@localhost temp]# cd bin

/usr/local/rss/bin

[root@localhost bin]# pwd

/usr/local/rss/bin

使用shopt设置cdable_vars也可以达到同样的效果

-*杂项变量

      

Table 3-8. Status variables

Variable

Meaning

HOME

Name of your home (login) directory

SECONDS

Number of seconds since the shell was invoked

BASH

Pathname of this instance of the shell you are running

BASH_VERSION

The version number of the shell you are running

BASH_VERSINFO

An array of version information for the shell you are running

PWD

Current directory

OLDPWD

Previous directory before the last cd command

 

 

§3.5  自定义和子程序

       执行命令是在子shell中执行。

*环境变量

       环境变量可以用于参数传递。比如vi emacsTERM来确定终端类型。Unix邮件程序通过EDITOR或者VISUAL来确定要使用的编辑器。所有变量需要通过export成为环境变量(除非设置了set -a or set -o allexport,这样会导入所有变量)。

 

export varnames

export wonderland=alice

给指定子程序定义:varname=value command

       TERM=trythisone  emacs  filename

Export或者export –p可以查看定义的环境变量。

一些标准变量:

Variable

Meaning

COLUMNS

The number of columns your display has[22]

EDITOR

Pathname of your text editor

LINES

The number of lines your display has

SHELL

Pathname of the shell you are running

TERM

The type of terminal that you are using

-*终端类型

       位于/usr/share/terminfoTERM类型的猜测办法暂略。

-*其他通用变量

 

*环境文件

       默认为.bashrc

 

阅读(8577) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~