shell environment

As we discussed earlier,the shell maintains a body of (大量)information during our shell session called the environment.Data stored in the environment is used by programs to determine facts about our configuration.While most programs use configuration files to store program setting,some programs will also look for values stored in the environment to adjust their behavior.Knowing this,we can use the environment to customize(定制) our shell experience.

 In this chapter,we will work with the following commands:

  • printenv-Print part or all of the environment
  • set-Set shell options
  • export-Export environment to subsequently(其后,随后,接着) executed programs导出环境变量,让随后执行的程序知道
  • alias-Create an alias for a command

What is stored in the environment variable?(什么存储在环境变量中?)

The shell stores two basic types of data in the environment,though,with bash,the types are largely indistinguishable(难区分的,不能分辨的).They are environment variables and shell variables.Shell variable are bits of data placed there by bash,and environment variables are basically everything else.In addition to variables,the shell also stores some programmatic data,namely aliases and shell functions.We covered aliases in Chapter6,and shell functions(which are related to shell scripting)will be covered in part5.

Check environment variables(检查环境变量)

We can use either the set builtin in bash or the printenv program to see what is stored in the environment.The set command will show both the shell and environment variables,while printenv will only display the latter(后者的,较后的).Since the list of environment contents will be fairly(公平地,相当地,简直,here is相当地) long,it is best to pipe the output of either((两者中)任一的,(否定句)也) command into less:

Doing so,we should get something that looks like this:

What we see is a list of environment variables and their values.For example,we see a variable called USER,which contains the value"darui".The printenv command can also list the value of a specific variable:

 

The set command,when used without options or arguments,will display both the shell and environment variables,as well as any defined shell functions.Unlike printenv,its output is courteously(有礼貌地,亲切地) sorted in alphabetical(按字母表顺序的) order:

It is also possible to view the contents of a variable using the echo command,like this:

One element of the environment that neither set nor printenv displays is aliases.To see them,enter the alias command without arguments:

Some funny variables(一些有趣的变量)

The environment contains quite a few variables,and though your environment may differ from the one presented here,you will likely see the following variables in your environment:

Table 12-1:Environment Variables

VariableContents
DISPLAY

The name of your display if you are running a graphical environment.

Usually this is ":o",meaning the first display generated(发电的)by the X server.

EDITORThe name of the program to be used for text editing.
SHELLThe name of your shell program
HOMEThe pathname of your home directory.
LANGDefines the character set and collation(核对,考订) order of your language.定义了字符集以及语言编码方式
OLD_PWDThe previous working directory.
PAGERThe name of the program to be used for paging output.This is often set to /usr/bin/less.
PATHA colon-separated(冒号分隔) list of directories that are searched when you enter the name of a executable program.由冒号分开的列表,当你输入可执行程序名后,会搜索这个目录列表
PS1Prompt String 1.This defines the contents of your shell prompt.As we will later see,this can be extensively(广大地,广泛地) customized(定制,定做).
PWDThe current working direcotry.
TEARMThe name of your terminal type.Unix-like systems support many terminal protocols;this variable sets the protocol to be used with your terminal emulator.
TZSpecifies your timezone.Most Unix-like systems maintain the computer's internal clock in Coordinated(协调的) Universal(全体的。广泛地,普遍地) Time(UTC)and then displays the local time by applying an offset(抵消,补偿) specified by this variable
USERYour user name.

Don't worry if some of these values are missing.They vary by distribution.

 

How to build shell environment?

When we log on to the system,the bash program starts,and reads a series of configuration scripts called startup files,which define the default environment shared by all users(这些文件定义了默认的可供所有用户共享的shell环境).This is followed by more startup files in our home directory that define our personal environment.The exact sequence(先后次序,顺序,连续) depends on  the type of shell session being started.There are two kinds:a login shell session and a non-login shell session.

A login shell session is one in which we are prompted for our user name and password;when we start a virtual console session,for example.A non-login shell seesion typically occurs when we launch a terminal session in the GUI.

Login shells read one or more startup files as shown in Table 12-2:

FileContents
/etc/profileA global configuration script that applies to all users
~/.bash_profileA user's personal startup file.Can be used to extand or override (不顾,不理)setting in the global configuration script.
~/.bash_loginIf~/.bash_profile is not found,bash attempts(企图,试图,尝试) to read this script.
~/.profileIf neither~/.bash_profile nor  ~/.bash_login is found,bash attempts to read this file.This is the default in Debian-based distributions,such as Ubuntu

Non-login shell sessions read the following startup files:

Table 12-3:Startup Files For Non-Login Shell Sessions

FileContents
/etc/bash.bashrcA global configuration script that applies to all users.
~/.bashrcA user's personal startup file.Can be used to extand or override settings in the global configuration script.

In addition to reading the startup files above,non-login shells also inherit(继承) the environment from their parent process,usually a login shell.

Take a look at your system and see which of these startup files you have.Remember-since most of the filenames listed above start with a period (meaning that they are hidden),you will need to use the "-a" option when using ls.

The ~/.bashrc file is probably the most important startup file from the ordinary user's point of view,since it is almost always read.Non-login shells read it by default and most startup files for login shells are written in such a way as to read the ~/.bashrc file as well.

The contents of a startup file

If we take a look inside a typical.bash_profile(taken from a CentOS 4 system),it looks something like this:

Lines that begin with a "#" are comments(注解,注释) and are not read by the shell.These are there for human readability.The first interesting thing occurs on the fourth line,with the following code:

This is called an if compound(复合的,混合的) command,which we will cover fully when we get to shell scripting in Part5,but for now we will translate:

We can see that this bit of code is how a login shell gets the contents of .bashrc.The next thing in our startup file has to do with the PATH variable.

Ever wonder how the shell knows where to find commands when we enter them on the command line?For example,when we enter ls,the shell does not search the entire computer to find /bin/ls(the full pathname of the ls command),rather,it searches a list of directories that are contained in the PATH variable.

The PATH variable is often(but not always,depending on the distribution)set by the /etc/profile startup file and with this code:

PATH is modified to add the directory $HOME/bin to the end of the list.This is an example of parameter expansion,which we touched on in Chapter 8.To demonstrate(论证,证明)how this works,try the following:

Using this technique,we can append text to the end of a variable's contents.By adding the string $HOME/bin to the end of the PATH variable's contents,the directory $HOME/bin is added to the list of directories searched when a command is entered.This means that when we want to create a directory within our home directory for storing our own private programs,the shell is ready to accommodate us.All we have to do is call it bin,and we're ready to go.

Note:Many distributions provide the PATH setting by default.Some Debian based distributions,such as Ubuntu,test for the existence of the ~/bin directory at login,and dynamically add it to the PATH variable if the directory is found.

Lastly,we have :

The export command tells the shell to make the contents of PATH available to child processes of this shell.

 

Modify the environment of shell

Since we know where the startup files are and what they contain,we can modify them to customize our environment.

Which file should we modify?

As a general rule,to add directories to your PATH,or define additional environment variables,place those changes in .bash_profiel(or equivalent(相等的,相当的),according to you distribution.For example,Ubuntu uses .profile.)For everything else,(对于其他的一切)place the changes in .bashrc.Unless you are the system administrator and need to change the defaults for all users of the system,restrict your modifications to the files in your home directory.It is certainly possible to change the files in /etc such as profile,and in many cases it would be sensible(明智的)to do so,but for now,let's play it safe.

 

Text editor

 To edit(i.e.,modify) the shell's startup files,as well as most of the other configuration files on the system,we use a program called a text editor.A text editor is a program that is,in some ways,like a word processor in that it allows you to edit the words on the screen with a moving cursor.It differs from a word processor by only supporting pure text,and often contains features designed for writing programs.Text editors are the central tool used by software developers to write code,and by system administrators to manage the configuration files that control the system.

There are a lot of different text editors available for Linux;your system probably has several installed.Why so many different ones?(为什么有这么多种呢?)Probably because programmers like writing them,and since programmers use them extensively,they write editors to express their own desires as to how they should work.(可能因为程序员喜欢编写它们,又因为程序员们会频繁地使用它们,所以程序员编辑器让它们按照程序员自己的愿望工作。)

Text editors fall into two basic categories(生物类别):graphical and text based.GNOME and KDE both include some popular graphical editors.GNOME ships with an editor called gedit,which is usually called "Text Editor"in the GNOME menu.KDE usually ships with three which are (in order of increasing complexity按照复杂度递增的顺序排列)kedit,kwrite,and kate.

There are many text-based editors.The popular ones you will encounter are nano,vi,and emacs.The nano editor is a simple,easy-to-use editor designed as a replacement for the pico editor supplied with the PINE email suite.The vi editor(on most Linux systems replaced by a program named vim,which is short for "Vi IMproved") is the traditional editor for Unix-like systems.It will be the subject of our next chapter.The emacs editor was originally written by Richard Stallman.It is gigantic(巨大的,庞大的),all-purpose,does-everything programming environment.While readily available,it is seldom installed on most Linux systems by default.

Use text editor

All text editors can be invoked from the command line by typing the name of the editor followed by the name of the file you want to edit.If the file does not already exist,the editor will assume that you want to create a new file.Here is an example using gedit:

This command will start the gedit text editor and load the file named "some_file",if it exists.

All graphical text editors are pretty self-explanatory(不解自明的,明显的),so we won't cover them here.Instead,we will concentrate (专心于,集中) on our first text-based text editor,nano.Let's fire up nano and edit the .bashrc file.But we do that,let's practice some "safe computing." Whenever we edit an important configuration file,it is always a good idea to create a backup copy of the file first.This protects us in case we mess the file up while editing.To create a backup of the .bashrc file,do this:

It doesn't matter what you call the backup file,just pick an understandable name.The extensions ".bak",".sav",".old",and ".orig" are all popular ways of indicating a backup file.Oh,and remember that cp will overwrite existing files silently.

Now that we have a backup file,we'll start the editor:

Once nano starts,we'll get a screen like this:

Note:If your system does not have nano installed,you may use a graphical editor instead.

The screen consists of a header at the top,the text of the file being edited in the middle and a menu of commands at the bottom.Since nano was designed to replace the text editor supplied with an email client,it is rather short on editing features.The first command you should learn in any text editor is how to exit the program.In the case of nano,you type Ctrl-x to exit.This is indicated in the menu at the bottom of the screen.The notation(记号,标记法)"^X" means Ctrl-x.This is a common notation for control characters used by many programs.

The second command we need to know is how to save our work.With nano it's Ctrl-o.With this knowledge under our belts(区域,地带),we're ready to some editing.Using the down arrow key and / or the PageDown key,move the cursor to the end of the file,then add the following lines to the .bashrc file:

 

Note:Your distribution may already include some of these,but duplicates(复制) won't hurt anything.

Here is the meaning of our additions:

Table 12-4:

LineMeaning
umask 0002Sets the umask to solve the problem with shared direcotries

export

HISTCONTROL=ignoredups

Causes the shell's history recording feature to ignore a command if the same command was just recorded.

使得shell的历史记录功能忽略一个命令,如果相同的命令已被记录

export HISTSIZE=1000Increases the size of the command history from the default of 500 lines to 1000 lines.
alias l.='ls -d .*  --color=auto'Creates a new command called "l."which displays all directory entries that begin with a dot.
alias ll='ls -l --color=auto'Creates a new command called "ll" which displays a long format directory listing.

As we can see,many of our additions are not intuitively(直觉地,直观地) obvious,so it would be a good idea to add some comments to our .bashrc file to help explain things to the humans.Using the editor,change our additions to look like this:

Ah,much better!With our changes complete,type Ctrl-o to save our modified .bashrc file,and Ctrl -x to exit nano.

 

Why Comments Are Important

Whenever you modify configuration files it's a good idea to add some comments to document your changes.Sure,you will remember what you changed tomorrow,but what about six months from now?Do yourself a favor and add some comments.While you're at it(当你意识到这一点的时候),it's not a bad idea to keep a log of what changes you make.

Shell scripts and bash startup files uses a '#' symbol to begin a comment.Ohter configuration files may use other symbols.Most configuration files will have comments.Use them as a guide.

You will often see lines in configuration files that are commented out to prevent them from being used by the affected program.This is done to give the reader suggestions for possible configruation choices or examples of correct configuration syntax.For example,the .bashrc file of Ubuntu 8.04 contains these lines:

The last three lines are valid(有效的)alias definitions that have been commented out.If you remove the leading "#" symbols from these three lines,a technique called uncommenting,you will activate the aliases.Conversely(相反地),if you add a "#" symbol to the beginning of  a line,you can deactivate a configuration line while preserving(保护,保存) the information it contains.

 

Active our modification

The changes we have made to our.bashrc will not take affect until we close our terminal session and start a new one,since the .bashrc file is only read at the beginning of a session.However,we can force bash to re-read the modified  .bashrc file with the following command:

After doing this,we should be able to see the effect of our changes.Try out one of the new aliases:

 

Sum up

In this chapter we learned an essential(必不可少的,绝对必要的) skill---editing configuration files with a text editor.Moving forward,as we read man pages for commands,take note of the environment variables that commands support.There may be a gem(宝石) or two.In later chapters,we will learn about shell functions,a powerful feature that you can also include in the bash startup files to add to you arsenal(兵工厂,军械库) of custom commands.

 

转载于:https://www.cnblogs.com/itmeatball/p/7573202.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值