Shell脚本学习笔记(Beginning Linux Programming 4th Chapter 2)

1、使用Shell编程、开发脚本的原因:简单易学,所有的Linux都装备,无需安装。

2、Shell由一系列小的脚本组成,并且可以根据需求进行任意组合、替换,很好地诠释了Linux的核心特性“Reuse”(代码重用)。

3、Shell是用户和Linux系统之间的一层应用层交互接口。

4、经典的Shell版本:

  • sh:Unix的Shell脚本,Bourne开发。
  • csh, tcsh, zsh,:Berkeley Unix的Shell,Bill Joy开发。
  • ksh, pdksh:商业Unix的Shell,David Korn开发。
  • bash:Bourne Again Shell,就是1L的那哥们开发的。GNU开源项目,借鉴了ksh,目前应用最为广泛。

5、在Linux等系统中,命令行Shell默认用/bin/sh表示,查看自己的Shell是哪个版本?

$ ls -alh /bin/sh
lrwxrwxrwx. 1 root root 4 May 30  2012 /bin/sh -> bash

6、查看Bash的版本:

$ /bin/bash -version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

不同版本的Shell,包含了不同的命令集合,或者命令的使用方式有细微变化。

7、Shell中的重定向,覆盖模式:

ls -alh > ./output

追加:

ls -alh >> ./output

8、默认的文件描述符:输入0,输出1,错误2。

一个常见的情况:gcc编译会出错,但是错误一般无法重定向到文件。

将输出、错误分别重定向到不同的文件中:

gcc -c 1>out 2>err

将输出、错误合并重定向到文件。

gcc -c xx.c > output 2>&1

9、重定向输入

more < ./a.c
#或者
cat a.c | more

10、上述那第二种方法,实际应该叫“管道”。

管道用分隔符“|”隔开,下面这个例子,将ps结果按照pid倒序排列,最后重定向到文件中。

ps | sort -k1,1nr > ps.out

11、管道的连接数量是无限的:

查看所有不同的进程名称,并去除名为sh的进程。

ps -xo comm | sort | uniq | grep -v sh | more

上述的sort和uniq是比较固定的用法,用于去重(uniq命令去重必须先sort)。

grep -v 的意思,-v是反向即打印未命中的行。以此方法去掉sh。

12、

 

Leave a Reply

Your email address will not be published. Required fields are marked *