文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>K shell program guide

K shell program guide

时间:2007-01-12  来源:darrenshen

Korn Shell (ksh) Programming http://www.bolthole.com/solaris/ksh.html   Learning the Korn Shell http://unix.org.ua/orelly/unix/ksh/index.htm   UNIX Shell Scripting Korn http://unix.ittoolbox.com/topics/t.asp?t=419&p=419&h1=419                      第四部分:SHELL介绍

                     第一讲:什么是Shell 

当我们登入unix之後, 第一个接触到的, 便是 Shell. 我们必须对它有点初步的认识才行. 

一. Shell 简介. 

unix系统分成三个重要的部份 

核心  
Shell  
工具程式  
核心的部份相当低阶, 操作者不易和它直接沟通, 因此, 必须要有一个友善的介面(interface), 使得操作时能更为方便, 这个介面便是 Shell. 

换言之, Shell 就是一个居於核心和操作者之间的一层使用者介面.  

那麽, 为何称它为 Shell 呢? Shell 的本意是 "壳" 的意思呢! 

没错, 在核心的外面, 包覆着一层外壳, 用来负责接收使用者输入的指令, 然後将指令解译成核心能够了解的方式, 传给核心去执行, 再将结果传回至预设的输出周边. 
例如: 键入 

ls -l  

shell 给你以下回应: 

            拥                        
档          有                                
案          档                               
种          案                   档案大小 最近修改的 
类 档案权限 数 拥有人   组别    (byte单位)日期及时间   档案名称 
drwxr-xr-x  14 root     root         1024 Jul 21 21:31 . 
drwxr-xr-x  17 root     root         1024 Apr 11 12:01 .. 
drwxr-xr-x   8 82       82           1024 Feb 25 19:23 apache 
-rw-r--r--   1 root     root      1335460 Feb 25 17:45 apache_1_3_4.tar.gz 
drwxr-xr-x   6 root     root         1024 Aug 31  1998 ftp 
drwxr-xr-x   5 root     root         1024 Aug 31  1998 httpd 
drwx------   2 james    james        1024 Apr 23 06:47 james 
drwxr-xr-x   2 root     root        12288 Aug 31  1998 lost+found 
drwxr-xr-x   2 msql     nobody       1024 Dec 28  1998 msql 
drwxr-xr-x  28 ols3     ols3         2048 Jul 19 21:38 ols3 
drwxr-xr-x   3 1022     nobody       1024 Jan 25 23:40 ols3cgi 
drwxrwxr-x   3 perl     ols3         1024 Feb  2 07:11 perl 
-rw-------   1 root     root      2097152 Jul 21 18:39 quota.group 
-rw-------   1 root     root      1278656 Jul 21 18:39 quota.user 
drwxrwxr-x   2 root     nobody       1024 May 11  1998 samba 
drwxr-xr-x   3 apache   nobody       1024 Feb 25 16:58 temp 
drwxrwxr-x   2 webadm   nobody       1024 Mar 14 16:34 webadm 

Shell 按着表现的方式与读取使用者输入种类的不同, 可分为二大类: 
Text base : 文字导向  
Graph base: 图型导向  
所谓 "读取使用者输入种类不同" 是指: 读取自键盘, 或读取自滑鼠, 其它 serial input, 萤幕触控等. 

这样说来, Shell 好像只是命令直译器罢了?!  
嗯, 这倒要按不同的 OS 所附给的 Shell 其功能和选择性的自由度而定. 

以 DOS 的 COMMAND.COM 而言, 它就是一个十足的命令直译器, 除了一点点 batch 档的能力之外, 它的功能并不多. Win 平台的 GUI, 则是一个图型式的命令直译器, 介面十分友善. 不过, 这二种 OS, 不能让你自由而简单地选择 Shell.(以前 DOS 有 4dos 可选用) 

由於 Unix 家族, 对 Shell 的处理, 采独立自由开放的方式, 因此, Shell 的种类相当地多, 更可以让人自由地更换(chsh). 

目前流行的 shell 有: 

Bourne shell : sh  
C shell : csh  
Korn shell: ksh (商业软体)  
tcsh (free)  
Bourne Again shell: bash (GNU)  
 
二. Shell 的简史 

第一个重要的 shell 是 Bourne shell (如此命名是为了纪念此 shell 的发明者 Steven Bourne), 1979 年第一个流行的 Unix 版本 7 发行时, 开始使用 Bourne shell.  

Bourne shell 的主档名为 sh, 因此, 日後人们便以 sh 为 Bourne shell 的主要识别名称. 

虽然 Unix 上的 shell 有许多种, 但 Bourne shell 的地位至今仍然没有改变. 许多 Unix 系统中仍然使用 sh 做为重要的管理工具. (它的工作从开机到关机, 几乎无所不包) 

第一个广为流行使用的 shell 变种是 C shell. C shell 主要附在 BSD 版的 Unix 系统中. 它的作者是柏克莱大学的 Bill Joy. C shell 主要是因为其语法和 C 语言相类似, 因而得名. 这使得 Unix 系统的程式师, 在学习 C shell 时, 感到相当地方便容易. 

以上这二种形成 shell 的二大主流, 後来的变种 shell 大都攫取这二种 shell 的优点. 

比如 Korn, tcsh 及 bash. 

Bash shell 是 GNU 计划的重要工具软体之一, 也是 GNU 作业系统中标准的 shell. 
Bash 在 1988 年诞生, 最初的作者是 Brian Fox, Chet Ramey 於 1989 加入, 现在官方正式的维护者是 Chet Ramey, 他的工作便是持续不断地增强 bash 的功能. 
1995~1996 期间推出 bash 2.0 , 在这之前, 广为使用的版本是 1.14.x, 它增加了许多新的功能, 以及更好的相容性. 
当然, Bash 是完全免费的, 它是 Open Source 的一员, 原始码全部开放. 

二. Bash 的功能. 

Bash 具有以下功能: 

相容於 Bourne shell (sh)  
包含有 C shell 以及 Korn shell 中最好的功能.  
具命令列编修的能力(您记得以前 DOS 中的 doskey 吗?)  
工作控制(job control)的能力, 可控制前景及背景程式  
具 shell 程式设计的能力, 可让您自订shell及设计程式, 管理系统.  
三. 新版的 Bash 哪里抓取? 

若欲抓取新版的 bash, 可至 http://www.gnu.org 或其 mirror 站台. 

中研院 FTP 也是不错的选择. ftp://ftp.sinica.edu.tw 或 ftp://linux.sinica.edu.tw 

三. 开始使用 Bash 

当你 login 进 unix 主机时, 便开始和 bash 互动, 一直到你 exit 主机(或按^D) 为止. 

Bash 的提示符号为$(代表一般身份使用者), 当您具有 root 权限时, 提示符号则变为 #. 

一旦出现提示符号时, 您便可以开始键入操作命令列(command line)了. 

命令可分为二大类: 

bash 内建的指令  
程式  
如果是 bash 内建的指令, 则由 bash shell 负责回应; 若是程式, 则 shell 会找出该程式, 然後将控制权交给核心, 由核心执行该程式, 执行完之後, 再将控制权交回给 shell. 

怎麽知道那些指令是 bash 内建的, 那些是程式呢? 通常用 "which 指令", 若没有任何回应, 表示是内建的指令(除非该指令错误、不存在, 或该程式不在预设的搜寻路径之内), 例如下: 

$/usr/ucb/which echo    [没有回应, 表示是内建的指令] 
  /usr/bin/echo
$ /usr/ucb/which ls 

/bin/ls 

四. 命令列的格式. 

命令列通常由好几个字串组成, 中间用空白或 tab 键分开. 如下所示: 

command options  arguments(或称为 parameters)  
命令 选项 参数  
rm -rf /home/ols3  

除了空白和 tab 键之外, 每一部份, 我们称之为 token, 比如上面的例子中, 便有三个 token: rm, -rf, /home/ols3. 

当键入此一命令列时, shell 首先将它分解成个别的 token, 然後判断是内建的指令, 或是程式, 再按之前提过的方式去执行. 

怎麽知道一个命令或程式, 它有那些选项和参数呢? 通常 man 一下该指令, 就可以得到了. 例如: 

man rm 

另外, 多行指令也可以一下全部写在同一命令列中, 只要中间用 ; 分开, 如: 

ls ; mkdir test ; clear 

五. 现行目录和自家目录. 

所谓现行目录(current directory)是指: 你现在所处的位置, 又称为工作目录(working directory). 

欲知现行目录为何? 可下 pwd 指令便知. 

所谓自家目录(home directory)是指: 当初 root 为你建立帐号时, 所指定给你的一个私人专用的目录, 也是你登入系统之後, 第一个进入的地方. 

欲知自家目录, 可用下列方式: 

cd    (然後直接按 Enter)  
cd ~    (~ 代表自家目录)  
cat /etc/passwd | grep 您的帐号  
相关的技巧 

cd ./myway (进入目前目录下的 myway 目录中)   
cd .. (回到上一层目录)  

六. 万用字元. 

如果命令列的参数中, 含有档名, 那麽万用字元(wildcards)可以带来十分便利的操作. (不过若使用不当, 也是恶梦的开始) 

如果各位以前有过 DOS 的操作经验, 应该还记得 * 及 ? 所代表的意义吧?!  

以下是 bash 中使用的万用字元: 

? 代表任何单一字元(character)  
* 代表任何字串 (注意: 0 个以上的字元, 例: *yes 将包含 yes 或 yes-or-not)  
[字元组合] 在中括号中的字元皆符合, 如: [a-z]代表所有的小写字母  
[!字元组合] 不在中括号中的字元皆符合, 如: [!0-9]代表非数字的字元皆符合  

  

七. 输入和输出与重新导向. 

当 unix系统完成开机之後, 预设上, 便开有三个档案, 这三个档案是做为输入、输出以及显示错误之用的.  

我们称之为: 

标准输入: 通常是键盘, 档案代码为 0  
标准输出: 通常是萤幕, 档案代码为 1  
标准错误: 通常标准输出相同(也就是萤幕), 档案代码为 2  
虽然系统已帮你设好了这三个档案, 但我们仍然可以视需要, 适时地改变输入,输出,及错误这三者至不同的地方. 这种改变标准输出入的动作, 我们称之为 "I/O 重新导向" (I/O Redirection). 

例如: 

ls -la > myfile 就是将查询的结果重新导向至 myfile 中(本来是应该出现在萤幕上的) 

cat myfile 便可以看见 ls -la 的结果. 

cat < myfile > youfile 就是将 myfile 的内容拷贝给 youfile. 

> 代表将输出转向 

< 代表将输入转向 

另一个会将输出入转向的机制是 "管线" (Pipelines). 

所谓的管线就是将一个程式的输出当成另一个程式的输入. 

例如: cat /etc/passwd | grep ols3 

上面这段指令的意思是说: 把 /etc/passwd 档的内容显示结果(即输出) 丢给 grep 这个指令当作输入值, 然後由 grep 从中找出包含关键字 ols3 的资料列. 

  

八. 前台与后台工作. 

unix 是多用户多任务的作业系统, 这意谓UNIX 可以让多人同时使用, 更可以同时执行许多程式. 

一般而言, 你所执行的指令会一直握着控制权, 一直到程式结束为止, 我们称为这样的执行工作是在前台工作(foreground jobs), 如果, 执行指令时, 你仍然可以再做其它的事情, 那我们就称它是在后台工作. 

通常比较耗时间的工作, 我们会把它丢到后台去执行, 而这期间, 我们仍然可以和 shell 继续沟通, 下达其它命令给 shell 去执行. 

例如: 我们想从中研院的 FTP 伺服器下载某一个目录中所有的档案, 但又不想等它执行完毕(因为这样耗时间,也很无聊), 可以用以下的方式来达成: 

ncftp -R ftp://linux.sinica.edu.tw/pub1/redhat/powertools & 

其中 & 这个符号便是将命令列丢到后台去执行的指令. 

如果您想离线之後, 仍然令系统继续传档, 可以在前面再加一个 nohup 的指令, 如下: 

nohup ncftp -R ftp://linux.sinica.edu.tw/pub1/redhat/powertools & 

nohup 是 no hangup 即不挂断之意. 

八. 特殊字元及引号. 

有许多字元, 对 shell 来说, 是具有特殊意义的. 详列於下: 

符号 意义  
~ 自家目录  
` 命令取代  
# 解  
$ 变数取值  
& 后台工作  
* 万用字元  
( 子shell开始  
) 子shell结束  
\ 使特殊字元恢复本意  
| 管线  
[ 字元组合开始  
] 字元组合结束  
{ 命令区块开始  
} 命令区块结束  
; 命令分隔号  
' 单引号(不具变数置换的功能)  
" 双引号(具置换的功能)  
< 输入转向  
> 输出转向  
/ 路径分隔号  
? 万用字元  
! 管线逻辑意义上的 NOT  
  Korn Shell执行命令的顺序

1.关键字,如if,for,function等

2.别名(Aliases)

3.内部命令,如cd, whence和函数等

4.函数Functions

5.脚本Scripts、在PATH中的可执行程序

※找到命令的根源用下面的命令:

whence -v command

或:

type command

Alias(别名)

alias aliasname=command

取消一个别名:

unalias aliasname

列出当前所有的别名:

alias

【TIP】

用来显式当前目录下的所有目录的别名:alias ldir='ls -l|grep ^d'

提问:alias|grep ^ls会看到:ls=/usr/bin/ls,请问:系统为什么要定义这个别名?

Functions(函数)

定义的位置:

Function可以在命令行、.kshrc(ENV文件,见下篇)或在shell script中定义

定义的方法:

function funcname {

shell commands

}

或:

funcname () {

shell commands

}

列出所有当前的functions

functions

取消一个function

unset -f funcname

输出一个function:

typeset -fx funcname

取消输出一个function:

typeset +fx funcname

※function是"typeset -f"的预定义的别名

Korn Shell 的选项

Korn Shell有一些选项,如果在.kshrc(ENV文件,见下篇)中设定他们,那么他们就是全局的,并且可以传递给subshell。

列出所有的Korn Shell选项:

set -o

设置一个选项

set -o OptionName

取消一个选项

set +o OptionName

Korn Shell 选项的意义

allexport 自动export随后定义地所有变量(文件名中不含有.).(等于set -a)

errexit 如果一个命令的返回值不为0,就执行错误陷阱(ERR trap)。但对profile文件例外。(等于set -e)

bgnice 后台进程以较低的优先级运行,这是缺省值

emacs 使用emacs风格的行内编辑器

gmacs 使用gmacs风格的行内编辑器

ignoreeof 遇到文件结束符时不退出shell。要想退出shell必须使用exit命令或者敲Ctrl-D 11次。

keyword 为了保持与Bourne shell的兼容性。(set -k)

markdirs 在完成文件名替换后在目录名后面加一个斜线(/)。

monitor Runs background jobs in a separate process and prints a line upon completion. (set -m)

noclobber 不能用>重定向符覆盖已经存在的文件。只能用>|来重写已经存在的文件。noexec 读入命令只检查它的语法但不执行。 (set -n)

noglob 禁止文件名替换。(set -f)

nolog 不在历史文件中保存函数的定义。

nounset 在试图扩展没有定义的变量时显示错误信息。(set -u)

privileged 禁止执行HOME/.profile file 并且使用/etc/suid _profile 而不是ENV文件。 (set -p)

verbose 显示shell读入的输入.(set -v)

trackall Designates each command as a tracked alias when first encountered.(set -h)

vi 使用vi风格的行内编辑器

viraw Processes each character as it is typed in vi mode.

xtrace 在运行命令前,先显示命令.(set -x)

※举例:使vi成为inline editor

set -o vi

Debuging(调试)

调试一个shell script的方法:

#set -o xtrace

然后再运行shell

或者直接执行

#ksh -x shellprog args



#sh -v shellprog args

Debug 一个function

#typeset -ft funcname

Prompts(提示)

PS1 主shell提示符(普通用户缺省是 $,而root缺省是#)

PS2 继续提示符( 缺省 > )

什么是继续提示符?

在命令行上输入

for i in 11 12 13 14 15 16

do

lspv hdisk$i

done

从第二行开始,屏幕最左面就是继续提示符。

PS3 在选择循环中的选择提示符(缺省是 #? )

PS4 调试提示符 (缺省是 + )

【tip】:命令行上提示主机名称和当前目录

export PS1="[`hostname`-"'$PWD]'

注意:一定是""包括``才能取得命令的结果,''包括变量才能随时更改变量的值

效果:

[hostname-/tmp]
  K shell program guide(1)

1)

Wildcard Matches
? Any single character
* Any string of characters
[set] Any character in set
[!set] Any character not in set
2)
Expression Matches
[abc] a, b, or c
[.,;] Period, comma, or semicolon
[-_] Dash and underscore
[a-c] a, b, or c
[a-z] All lowercase letters
[!0-9] All non-digits
[0-9!] All digits and exclamation point
[a-zA-Z] All lower- and uppercase letters
[a-zA-Z0-9_-] All letters, all digits, underscore, and dash

3)

Utility Purpose
cat Copy input to output
grep Search for strings in the input
sort Sort lines in the input
cut Extract columns from input
sed Perform editing operations on input
tr Translate characters in the input to other characters
4)
fc -l
fc -e - number
5)
user's environment file is .profile.
6)Built-in Commands and Keywords

Here is a summary of all built-in commands and keywords.

Command Chapter Summary
: 7 Do nothing (just do expansions of arguments).
. 4 Read file and execute its contents in current shell.
alias 3 Set up shorthand for command or command line.
bg 8 Put job in background.
break 5

Exit from surrounding for, select, while, or until loop.

case 5 Multi-way conditional construct.
cd 1 Change working directory.
continue

Skip to next iteration of for, select, while, or until loop.

echo 4 Expand and print arguments (obsolete).
exec 9 Replace shell with given program.
exit 5 Exit from shell.
export 3 Create environment variables.
eval 7 Process arguments as a command line.
fc 2 Fix command (edit history file).
fg 8 Put background job in foreground.
for 5 Looping construct.
function 4 Define function.
getopts 6 Process command-line options.
if 5 Conditional construct.
jobs 1 List background jobs.
kill 8 Send signal to process.
let 6 Arithmetic variable assignment.
newgrp
Start new shell with new group ID.
print 1 Expand and print arguments on standard output.
pwd 1 Print working directory.
read 7 Read a line from standard input.
readonly 6 Make variables read-only (unassignable).
return 5 Return from surrounding function or script.
select 5 Menu generation construct.
set 3 Set options.
shift 6 Shift command-line arguments.
time
Run command and print execution times.
trap 8 Set up signal-catching routine.
typeset 6 Set special characteristics of variables.
ulimit 10 Set/show process resource limits.
umask 10 Set/show file permission mask.
unalias 3 Remove alias definitions.
unset 3 Remove definitions of variables or functions.
until 5 Looping construct.
wait 8 Wait for background job(s) to finish.
whence 3 Identify source of command.
while 5 Looping construct.
7)
Built-in Shell Variables
Variable Chapter Meaning
# 4 Number of arguments given to current process.
-
Options given to shell on invocation.
? 5 Exit status of previous command.
$ 8 Process ID of shell process.
_
Last argument to previous command.
! 8 Process ID of last background command.
CDPATH 3 List of directories for cd command to search.
COLUMNS 3

Width of display in columns (for editing modes and select).

EDITOR 2

Used to set editing mode; also used by mail and other programs.

ERRNO A Error number of last system call that failed.
ENV 3

Name of file to run as environment file when shell is invoked.

FCEDIT 2 Default editor for fc command.
FPATH 4 Search path for autoloaded functions.
IFS 7

Internal field separator: list of characters that act as word separators. Normally set to SPACE, TAB, and NEWLINE.

HISTFILE 2 Name of command history file.
HISTSIZE 2 Number of lines kept in history file.
HOME 3 Home (login) directory.
LINENO 9 Number of line in script or function that just ran.
LINES 3 Height of display in lines (for select command).
MAIL 3 Name of file to check for new mail.
MAILCHECK 3 How often (in seconds) to check for new mail.
MAILPATH 3

List of file names to check for new mail, if MAIL is not set.

OLDPWD 3 Previous working directory.
OPTARG 6 Argument to option being processed by getopts.
OPTIND 6 Number of first argument after options.
PATH 3 Search path for commands.
PS1 3 Primary command prompt string.
PS2 3 Prompt string for line continuations.
PS3 5 Prompt string for select command.
PS4 9 Prompt string for xtrace option.
PPID 8 Process ID of parent process.
PWD 3 Current working directory.
RANDOM 9

Random number between 0 and 32767 (2215-1).

REPLY 5,7

User's response to select command; result of read command if no variable names given.

SECONDS 3 Number of seconds since shell was invoked.
SHELL 3 Full pathname of shell.
TMOUT 10

If set to a positive integer, number of seconds between commands after which shell automatically terminates.

VISUAL 2 Used to set editing mode.

8)Test Operators

These are the operators that are used with the [[...]] construct. They can be logically combined with && ("and") and || ("or") and grouped with parenthesis.

Operator True If...
-a file file exists.
-b file file is a block device file.
-c file file is a character device file.
-d file file is a directory.
-f file file is a regular file.
-g file file has its setgid bit set.
-k file file has its sticky bit set.
-n string string is non-null.
-o option option is set.
-p file file is a pipe or named pipe (FIFO file).
-r file file is readable.
-s file file is not empty.
-t N File descriptor N points to a terminal.
-u file file has its setuid bit set.
-w file file is writeable.
-x file

file is executable, or file is a directory that can be searched.

-z string string is null.
-G file file's group ID is the same as that of the shell.
-L file file is a symbolic link.
-O file file is owned by the shell's user ID.
-S file file is a socket.
fileA -nt fileB fileA is newer than fileB.
fileA -ot fileB fileA is older than fileB.
fileA -ef fileB

fileA and fileB point to the same file.

string = pattern

string matches pattern (which can contain wildcards).

string != pattern string does not match pattern.
stringA < stringB

stringA comes before stringB in dictionary order.

stringA > stringB

stringA comes after stringB in dictionary order.

exprA -eq exprB

Arithmetic expressions exprA and exprB are equal.

exprA -ne exprB

Arithmetic expressions exprA and exprB are not equal.

exprA -lt exprB exprA is less than exprB.
exprA -gt exprB exprA is greater than exprB.
exprA -le exprB exprA is less than or equal to exprB.
exprA -ge exprB exprA is greater than or equal to exprB.

9)Typeset Options

These are arguments to the typeset command.

Option Meaning

With no option, create local variable within function.
-L Left justify and remove leading blanks.
-R Right justify and remove trailing blanks.
-f With no arguments, prints all function definitions.
-f fname Prints the definition of function fname.
+f Prints all function names.
-ft Turns on trace mode for named function(s).
+ft Turns off trace mode for named function(s).
-fu Defines given name(s) as autoloaded function(s).
-i Declare variable as an integer.
-l Convert all letters to lowercase.
-r Make variable read-only.
-u Convert all letters to uppercase.
-x

Export variable, i.e., put in environment so that it is passed to subshells

10)

Substitution Operators
Operator Substitution
${varname:-word}

If varname exists and isn't null, return its value; otherwise return word.

Purpose:

Returning a default value if the variable is undefined.

Example:

$ evaluates to 0 if count is undefined.

${varname:=word}

If varname exists and isn't null, return its value; otherwise set it to word and then return its value.[7]

Purpose:

Setting a variable to a default value if it is undefined.

Example:

$ sets count to 0 if it is undefined.

${varname:?message}

If varname exists and isn't null, return its value; otherwise print varname: followed by message, and abort the current command or script. Omitting message produces the default message parameter null or not set.

Purpose:

Catching errors that result from variables being undefined.

Example:

{count:?" undefined!" } prints "count: undefined!" and exits if count is undefined.

${varname:+word}

If varname exists and isn't null, return word; otherwise return null.

Purpose:

Testing for the existence of a variable.

Example:

$ returns 1 (which could mean "true") if count is defined.

 

 

相关阅读 更多 +
排行榜 更多 +
挖掘机卡车

挖掘机卡车

模拟经营 下载
我的汤姆猫小米版

我的汤姆猫小米版

模拟经营 下载
我的小小邮轮

我的小小邮轮

模拟经营 下载