首页 | 程式人生 | 原创下载 | 技术文档 | 留言我们 | 关于我们

Bash学习笔记(二)

作者: phanrider        2006-06-09

shell内部命令的优先级别分别是:
别名->关键字->函数->内置命令->脚本或可执行程序

1,基本
看一个命令的类型,用type command 即可



[phanrider@redhat ~]$ type ls
ls is aliased to `ls --color=tty' #ls是个别名



2,别名与关键的比较
我们先看if这个关键字,当有了别名if后,会怎么样呢?



[phanrider@redhat ~]$ type if
if is a shell keyword #if是个关键字
[phanrider@redhat ~]$ if [ 1 -lt 2 ]; then echo ok; fi
ok
[phanrider@redhat ~]$ alias if="echo 'print from alias'" #生成别名if
[phanrider@redhat ~]$ if [ 1 -lt 2 ]; then echo ok; fi
-bash: syntax error near unexpected token `then' #Bash 报错
[phanrider@redhat ~]$ if
print in alias #这里if是个别名了
[phanrider@redhat ~]$ type if
if is aliased to `echo 'print from alias'' #用type查看,确实是个关键字



从上可以看出,别名的优先级大于关键字。

3,关键字与函数的比较
一般的新建函数名与关键字同名是没有用的,只有用关键字function



[phanrider@redhat ~]$ type if
if is a shell keyword #if是个关键字
[phanrider@redhat ~]$ if()
-bash: syntax error near unexpected token `)' #bash 报错
[phanrider@redhat ~]$ function if()
> {
> echo "abc"
> } #新建成功
[phanrider@redhat ~]$ if [ 1 -lt 2 ];then echo "ok" ; fi
ok #没有调用函数,还是调用的关键字
[phanrider@redhat ~]$



一样可以看出,关键字的优先级大于函数

4,函数与内置命令的比较



[phanrider@redhat ~]$ type test
test is a shell builtin #test是个内置命令
[phanrider@redhat ~]$ test 1 -lt 2 && echo ok
ok
[phanrider@redhat ~]$ test()
> {
> echo "print from function"
> } #新建一个test函数
[phanrider@redhat ~]$ test
print in function #再次执行test,得到是函数的输出
[phanrider@redhat ~]$ type test
test is a function
test ()
{
echo "print from function"
} #确实为函数了
[phanrider@redhat ~]$



从上可以看出,函数优先级大于内置命令

5,内置命令与脚本或可执行程序
这个一般都应当会知道的,还是看段代码吧



[phanrider@redhat ~]$ cat > echo <<EOF
> echo "print from echo script"
> EOF
[phanrider@redhat ~]$ chmod u+x echo
[phanrider@redhat ~]$ ll echo
-rwxrw-r-- 1 phanrider phanrider 26 Jun 9 12:16 echo
[phanrider@redhat ~]$ echo #这是内置命令

[phanrider@redhat ~]$ ./echo #这是sh脚本
print from test.sh
[phanrider@redhat ~]$



明显看出来了,不然调用不到同名的echo脚本


→返回←

红蜻蜓工作室版权所有
Copyright © 1999-2025 Reddragonfly & Studio All Rights Reserved.
如有任何问题及建议请留言红蜻蜓工作室