Chinaunix首页 | 论坛 | 博客
  • 博客访问: 98551
  • 博文数量: 18
  • 博客积分: 2264
  • 博客等级: 大尉
  • 技术积分: 270
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-13 21:46
文章分类

全部博文(18)

文章存档

2010年(1)

2009年(1)

2008年(16)

我的朋友

分类:

2009-05-16 10:18:46

shell中处理命令的顺序

肠子(changzi100)
mailto: changzi100@yahoo.com.cn


命令可能是一个关键词(if, while, function, untill等),一个别名(如:alias ll='ls -l'),一个函数(如:function hello { echo "Hello"; }),一个内置命令(cd, type等),应用程序(可执行程序或shell脚本)。

shell会按照命令的类型按先后顺序来执行它们。下面会用实验来检验一下。

以下摘自《Learning the bash shell, 3rd Edition》
1, Aliases

2, Keywords such as function and several others, like if and for

3, Functions

4, Built-ins like cd and type

5, Scripts and executable programs, for which the shell searches in the directories listed in the PATH environment variable


实验环境:
$ bash --version
GNU bash, version 3.2.33(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.

实验验证
1,首先比较“别名”和“关键词”
输入命令alias会看到当前系统中的别名
$ alias
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias vi='vim'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
看一下if命令
$ if [ 2 -gt 1 ]
> then
> echo "right"
> fi
right
$
下面输入一个新的“别名”if,此时与关键词重叠,看看接下来会执行哪个命令
$ if [ 2 -gt 1 ]
alias [ 2 -gt 1 ]
$
可以看到再次执行if命令时是按照别名的方式输出,而没有出现PS2的提示符“>”。
说明了shell执行的顺序是先“别名”,后“关键词”。

2,“关键词”和“函数”
输入关键词while回车后,会出现PS2的提示符“>”
$ while
>
下面用while做为名称写一个函数
$ function while { echo "This is a Function"; }
$ while
>
可以看到执行命令while时仍按照“关键词”的优先级,而没有按函数执行,说明shell的执行顺序是先“关键词”后“函数”。

3,“函数”和“内置命令”
type是shell的一个内置命令。
$ type type
type is a shell builtin
$ type file
file is /usr/bin/file
$ type ls
ls is aliased to `ls --color=auto'
下面写了一个以type为名称的函数
$ function type { echo "This is a Function"; }
$ type
This is a Function
$ type tyep
This is a Function
$ type ls
This is a Function
可以看到此时是以函数方式执行命令tyep,说明shell的执行顺序是先“函数”,后内置命令。

4,“内置命令”与“脚本”
用一个比较熟悉的内置命令cd,用法就不说了,呵呵。
$ type cd
cd is a shell builtin
接下来写一个脚本也叫cd
$ cat cd
#!/bin/bash
echo "This is a shell script."
$
执行cd命令时会有什么现像?
下面我们关闭内置命令cd后看看现像
$ enable -n cd
$ cd
bash: cd: command not found

接下来给脚本执行权限,并放入到PATH路径中
$ cd
This is a shell script.
$
看到了,此时执行的是脚本。

以上说明shell的执行顺序是先“内置命令”,后“脚本”

好吧,只写这些,验证一下,针对不同顺序的比较就留给大家经练习喽,比如“内置函数”与“别名”的比较之类。

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