Linux里有一些特殊的命令,称为内置命令(直接内置在BASH解释器中),它们天生就与其他的普通命令不同,因为它们从系统启动成功的那一刻就已经在内存里安家了。
当其他普通命令还在慢悠悠地从硬盘上读取程序文件加载到内存中时,内置命令已经早早地从内存中奔赴到CPU中,因此内置命令的执行效率要远远高于普通命令。
当然这其中有些命令更为特殊,比如echo命令、pwd命令、kill命令等,它们既有内置命令版本,又有普通命令版本,两种格式的命令其用法是一样的。我们能在磁盘上找到它们的程序文件/bin/echo、/bin/pwd、/bin/kill。一般情况下,优先使用内置命令,除非你显式地执行/bin/echo这种全路径命令。
表12-1展示的是常用的Linux内置命令。
表12-1 Linux常用的内置命令



【功能说明】
help命令可用于查看内置命令的帮助文档。
【语法格式】
help [选项] [内置命令]
【选项说明】
表12-2针对该命令的参数选项进行了说明。
表12-2 help命令的参数选项及说明

【使用范例】
**范例12-1:**查看所有内置命令。
[root@centos7 ~]# help #使用help命令查看Linux的所有内置命令。
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
These shell commands are defined internally. Type `help' to see this list.
Type `help name' to find out more about the function `name'.
Use `info bash' to find out more about the shell in general.
Use `man -k' or `info' to find out more about commands not in this list.
A star (*) next to a name means that the command is disabled.
job_spec [&] history [-c] [-d offset] [n] o>
(( expression )) if COMMANDS; then COMMANDS; [ >
. filename [arguments] jobs [-lnprs] [jobspec ...] or>
: kill [-s sigspec | -n signum |>
[ arg... ] let arg [arg ...]
[[ expression ]] local [option] name[=value] ..>
alias [-p] [name[=value] ... ] logout [n]
bg [job_spec ...] mapfile [-n count] [-O origin]>
bind [-lpvsPVS] [-m keymap] [-f> popd [-n] [+N | -N]
break [n] printf [-v var] format [argume>
builtin [shell-builtin [arg ...> pushd [-n] [+N | -N | dir]
caller [expr] pwd [-LP]
case WORD in [PATTERN [| PATTER> read [-ers] [-a array] [-d del>
cd [-L|[-P [-e]]] [dir] readarray [-n count] [-O origi>
command [-pVv] command [arg ...> readonly [-aAf] [name[=value] >
compgen [-abcdefgjksuv] [-o opt> return [n]
complete [-abcdefgjksuv] [-pr] > select NAME [in WORDS ... ;] d>
compopt [-o|+o option] [-DE] [n> set [-abefhkmnptuvxBCHP] [-o o>
continue [n] shift [n]
coproc [NAME] command [redirect> shopt [-pqsu] [-o] [optname ..>
declare [-aAfFgilrtux] [-p] [na> source filename [arguments]
dirs [-clpv] [+N] [-N] suspend [-f]
disown [-h] [-ar] [jobspec ...]> test [expr]
echo [-neE] [arg ...] time [-p] pipeline
enable [-a] [-dnps] [-f filenam> times
eval [arg ...] trap [-lp] [[arg] signal_spec >
exec [-cl] [-a name] [command [> true
exit [n] type [-afptP] name [name ...]
export [-fn] [name[=value] ...]> typeset [-aAfFgilrtux] [-p] na>
false ulimit [-SHacdefilmnpqrstuvx] >
fc [-e ename] [-lnr] [first] [l> umask [-p] [-S] [mode]
fg [job_spec] unalias [-a] name [name ...]
for NAME [in WORDS ... ] ; do C> unset [-f] [-v] [name ...]
for (( exp1; exp2; exp3 )); do > until COMMANDS; do COMMANDS; d>
function name { COMMANDS ; } or> variables - Names and meanings>
getopts optstring name [arg] wait [id]
hash [-lr] [-p pathname] [-dt] > while COMMANDS; do COMMANDS; d>
help [-dms] [pattern ...] { COMMANDS ; }
**范例12-2:**查看help命令的使用方法。
[root@centos7 ~]# help help #“help + 内置命令”这种格式能够查看内置命令的帮助,同时help本身也是内置命令。
help: help [-dms] [pattern ...]
Display information about builtin commands.
Displays brief summaries of builtin commands. If PATTERN is
specified, gives detailed help on all commands matching PATTERN,
otherwise the list of help topics is printed.
Options:
-d output short description for each topic #输出内置命令的简单描述。
-m display usage in pseudo-manpage format #以man帮助的格式显示。
-s output only a short usage synopsis for each topic matching #只输出命令的使用语法。
PATTERN
Arguments:
PATTERN Pattern specifiying a help topic
Exit Status:
Returns success unless PATTERN is not found or an invalid option is given.
**范例12-3:**查看cd命令的帮助文档。
[root@centos7 ~]# help cd #查看cd命令的帮助文档。
cd: cd [-L|[-P [-e]]] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed
-P use the physical directory structure without following symbolic
links
-e if the -P option is supplied, and the current working directory
cannot be determined successfully, exit with a non-zero status
The default is to follow symbolic links, as if `-L' were specified.
Exit Status:
Returns 0 if the directory is changed, and if $PWD is set successfully when
-P is used; non-zero otherwise.
[root@centos7 ~]# help -d cd #输出内置命令的简单描述。
cd - Change the shell working directory.
[root@centos7 ~]# help -m cd #以man帮助的格式显示。
NAME
cd - Change the shell working directory.
SYNOPSIS
cd [-L|[-P [-e]]] [dir]
DESCRIPTION
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed
-P use the physical directory structure without following symbolic
links
-e if the -P option is supplied, and the current working directory
cannot be determined successfully, exit with a non-zero status
The default is to follow symbolic links, as if `-L' were specified.
Exit Status:
Returns 0 if the directory is changed, and if $PWD is set successfully when
-P is used; non-zero otherwise.
SEE ALSO
bash(1)
IMPLEMENTATION
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[root@centos7 ~]# help -s cd #只输出命令的使用语法。
cd: cd [-L|[-P [-e]]] [dir]
**范例12-4:**在Shell脚本中使用占位符的例子。
if [ $i -eq 1 ] #条件表达式。
then
: #在Shell脚本里若用到了if判断语句,那么判断成功后通常会执行某些操作,但有时会不知道执行实名操作或者不需要执行某些操作。但是又碍于if语句的固定语法格式,不得不写一个命令占位置,因为这一行如果没有内容就会语法报错,此时就会用到":"这个占位符,不过请放心,这个命令不会对叫你的Shell脚本造成任何影响,其有点像其他编程语言的pass字段一样。
else
echo "Hello World"
fi
“.”和source常用于加载或执行Shell脚本,但是其与常规的执行Shell脚本的方法又不太一样。下面分别对比来看以下。
通常,在bash的条件结构和流程控制结构中都要进行各种测试,然后根据测试结果执行不同的操作,有时也会与if等条件语句相结合完成测试判断,以减少程序运行的错误。
执行条件测试表达式之后通常会返回“真”或“假”,就像执行命令后的返回值0表示真,非0表示假一样。
条件测试常用的语法如下:
**注意:**中括号内部的两端要有空格,[]和test等价,即test的所有判断选项都可以直接在[]里使用,但是推荐使用[]。
**范例12-5:**条件测试。
[root@centos7 ~]# test -f file && echo true || echo false #如果file文件存在并且是普通文件就为真,因为file文件不存在,所以输出了false。
false
[root@centos7 ~]# touch file #现在创建不存在的普通文件file。
[root@centos7 ~]# test -f file && echo true || echo false #因为file文件存在,所以输出了true。
true
[root@centos7 ~]# [ -f /tmp/neteagle.txt ] && echo 1 || echo 0 #如果/tmp/neteagle.txt文件存在并且是普通文件则为真,因为该文件不存在,所以输出量0。
0
[root@centos7 ~]# touch /tmp/neteagle.txt #创建文件。
[root@centos7 ~]# [ -f /tmp/neteagle.txt ] && echo 1 || echo 0 #因为文件存在,所以输出了1。
1
【功能说明】
alias命令用于查看或设置系统命令别名;unalias命令用于取消系统命令别名。
【语法格式】
alias [命令别名]=[命令语句]
unalias [命令别名]
【使用范例】
**范例12-6:**显示系统所有的命令别名。
[root@centos7 ~]# alias #不接任何参数表示显示所有的命令别名。
alias cp='cp -i'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
**范例12-7:**自定义别名。
[root@centos7 ~]# alias rm='echo "Do not use rm."' #为echo "Do not use rm."命令语句定义一个别名称为rm,后面单引号里的命令语句必须是可以执行的。
[root@centos7 ~]# rm #以后执行rm命令,就会执行echo "Do not use rm."这条命令量。
Do not use rm.
[root@centos7 ~]# alias rm #查询rm指代的命令语句。
alias rm='echo "Do not use rm."'
[root@centos7 ~]# alias eth0='cat /etc/sysconfig/network-scripts/ifcfg-eth0' #定义eth0别名。
[root@centos7 ~]# eth0
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=eth0
#UUID*=b21930c4-a2db-47e7-acfa-a2d9072882ed
DEVICE=eth0
ONBOOT=yes
IPADDR=10.0.0.201
PREFIX=24
GATEWAY=10.0.0.254
DNS1=223.5.5.5
IPV6_PRIVACY=no
从该例也可以看出,别名有如下作用。
**范例12-8:**删除命令别名。
[root@centos7 ~]# unalias eth0 #删除别名使用unalias。
[root@centos7 ~]# alias eth0 #再次查询已经没有eth0的别名。
-bash: alias: eth0: not found
【功能说明】
bg命令用于将前台执行任务转入后台,或者将后台暂停的任务运行起来;fg命令和bg命令相反,它是将后台任务调到前台来执行;jobs命令可以用于查看后台任务列表。
【语法格式】
bg [任务序列号]
fg [任务序列号]
jobs
【使用范例】
**范例12-9:**管理后台任务。
[root@centos7 ~]# nc -l 12345 #该命令执行完,会在前台一直显示。
^Z #使用Ctrl+z将前台任务转入后台,但同时任务变为暂停状态。
[1]+ Stopped nc -l 12345
[root@centos7 ~]# jobs #jobs命令用于查看任务列表,[1]为任务序列号。
[1]+ Stopped nc -l 12345
[root@centos7 ~]# bg #bg命令可以将后台暂停的任务运行起来,bg 1表示启动第一个任务,因为任务列表只有一个任务,所以简写为bg。
[1]+ nc -l 12345 &
[root@centos7 ~]# jobs
[1]+ Running nc -l 12345 & #此时任务状态为Running。
[root@centos7 ~]# fg fg命令可以将后台命令调入前台。
nc -l 12345
^C #此时这个命令又挂起在前台了,使用Ctrl+c终止。
**范例12-10:**快捷创建后台任务。
[root@centos7 ~]# nc -l 12345 & #其实可以直接使用&将任务放入后台,并且任务状态是运行的,比前面的方法简单多了。
[1] 2269
[root@centos7 ~]# jobs
[1]+ Running nc -l 12345 &
[root@centos7 ~]# kill %1 #这是一种快速结束后台进程的方法,kill %[任务序列号]
[root@centos7 ~]# jobs
[1]+ Terminated nc -l 12345
**范例12-11:**通过break命令跳出整个循环。
[root@centos7 ~]# vim break.sh
#!/bin/bash
for((i=0;i<=5;i++))
do
if [ $i -eq 3 ] ;then
break; #跳出整个循环,继续执行循环外后面的程序。
fi
echo $i
done
echo "ok"
:wq
脚本执行结果如下:
[root@centos7 ~]# bash break.sh
0
1
2
ok
**范例12-12:**使用continue命令进入下一次循环。
[root@centos7 ~]# cp break.sh continue.sh
[root@centos7 ~]# vim continue.sh
#!/bin/bash
for((i=0;i<=5;i++))
do
if [ $i -eq 3 ] ;then
continue; #结束本次循环,继续下一次循环。
fi
echo $i
done
echo "ok"
:wq
脚本执行结果如下:
[root@centos7 ~]# bash continue.sh
0
1
2
4
5
ok