内建命令指的就是包含在Bash工具集中的命令.这主要是考虑到执行效率的问题--内建命令将
比外部命令的执行得更快,外部命令通常需要fork出一个单独的进程来执行.另外一部分原因
是特定的内建命令需要直接存取shell内核部分.
当一个命令或者是shell本身需要初始化(或者创建)一个新的子进程来执行一个任务的时候,这
种行为被称为forking.这个新产生的进程被叫做子进程,并且这个进程是从父进程中分离出来
的.当子进程执行它的任务时,同时父进程也在运行.
注意:当父进程取得子进程的进程ID的时候,父进程可以传递给子进程参数,而反过来则不行.
这将产生不可思议的并且很难追踪的问题.
Example 11-1 一个fork出多个自己实例的脚本
################################Start Script#######################################
#!/bin/bash
# spawn.sh
PIDS=$(pidof sh $0) # Process IDs of the various instances of this script.
P_array=( $PIDS ) # Put them in an array (why?).
echo $PIDS # Show process IDs of parent and child processes.
let "instances = ${#P_array[*]} − 1" # Count elements, less 1.
# Why subtract 1?
echo "$instances instance(s) of this script running."
echo "[Hit Ctl−C to exit.]"; echo
sleep 1 # Wait.
sh $0 # Play it again, Sam.
exit 0 # Not necessary; script will never get to here.
# Why not?
# After exiting with a Ctl−C,
#+ do all the spawned instances of the script die?
# If so, why?
# Note:
# −−−−
# Be careful not to run this script too long.
# It will eventually eat up too many system resources.
# Is having a script spawn multiple instances of itself
#+ an advisable scripting technique.
# Why or why not?
#Generally, a Bash builtin does not fork a subprocess when it executes within a script. An external system
#+command or filter in a script usually will fork a subprocess.
################################End Script#########################################
一般的,脚本中的内建命令在执行时将不会fork出一个子进程.但是脚本中的外部或过滤命令
通常会fork一个子进程.
一个内建命令通常与一个系统命令同名,但是Bash在内部重新实现了这些命令.比如,Bash的
echo命令与/bin/echo就不尽相同,虽然它们的行为绝大多数情况下是一样的.
1 #!/bin/bash
2
3 echo "This line uses the /"echo/" builtin."
4 /bin/echo "This line uses the /bin/echo system command."
关键字的意思就是保留字.对于shell来说关键字有特殊的含义,并且用来构建shell的语法结构.
比如,"for","while","do"和"!"都是关键字.与内建命令相同的是,关键字也是Bash的骨干部分,
但是与内建命令不同的是,关键字自身并不是命令,而是一个比较大的命令结构的一部分.
我们可利用type -a <command>来查看该命令是哪种类型,如:type -a echo type -a read etc.
buildin 命令主要有以下这些:
IO:echo printf read
Filesystem:cd pwd pushd popd dirs
Variables:let eval set unset export declare typeset readonly getopts
Script Behavor:source exit exec shopt caller
Commands:true false type hash bind help
Job control:jobs disown fg bg wait suspend logout times kill command builtin enable autoload
from abs_guide_en