shell script小结
发现了一个巨赞的shell入门攻略,http://nixsrv.com/llthw, learn Linux the hard way, 虽然用的是bash做示例,但是大部分内容对于所有的shell都是适用的。
1. IO内容的导入导出:
ls > myfiles #Note if 'myfiles' file exist in your current directory it will be overwritten without any type of warning.
date >> myfiles #To output Linux-commands result (output of command or shell script) to END of file. Note that if file exist , it will be opened and new information/data will be written to END of file, without losing previous information/data, And if file is not exist, then new file is created. For e.g. To send output of date command to already exist file give command
cat < myfiles #o take input to Linux-command from file instead of key-board. need to think about the difference between cat < myflie VS cat myfile. < filename本质上是把file里面的内容redirect到input中,source是file而非pipe或者tty,在很多命令中会区分input stream来自于一个文件还是来自于Pipe/tty。
2. filter文件的部分行
tail +20 < hotel.txt | head -n30 >hlist
3. run script on the backend
$ ls / -R | wc -l &
The ampersand (&) at the end of command tells shells start process (ls / -R | wc -l) and run it in background takes next command immediately.
4. 判断相等或者文件是否存在
http://www.freeos.com/guides/lsst/ch03sec02.html
5. 命令参数用{}扩展
vimdiff /tmp/output{1,2} 等价于 vimdiff /tmp/output1 /tmp/output2. 而且{}扩展支持嵌套,所以可以echo abc{d,e,{f,g,h}},很有用。
6. difference between shell variable and environment variable
shell variable是只对于当前shell instance有效,常常在shell run的过程中被修改,大部分小写。而environment variable主要是永久性的变量(比如Home directory, login username等),大部分大写。
7. difference between tee and redirection >(>)
在使用pipe的过程中,经常需要把一部分的output存入外部文件中,比较常用的方式是通过>或者>>来操作,比如cat file1 > file2. 但是linux中有一个专门的程序tee可以把Input stream转化成output stream然后存入文件中,比如cat file1 | tee file2.不同之处就是tee的output不但存入文件,而且也输出到了standard output,可以被之后的pipe使用。
8. linux system的启动过程:http://www.debian.org/doc/manuals/debian-reference/ch03.en.html (debian system's boot strap process)
9. process的执行过程,以ls -ltr为例:
- 用户输入命令ls -ltr,回车
- control passed to shell, shell fork a new process(clone父进程到新的memory location)
- 子进程复制所有父进程的环境变量和堆栈信息,执行ls程序
- 子进程返回exit code给shell,shell赋值给$?,然后进入下一循环。
life cycle of process: http://www.linux-tutorial.info/modules.php?name=MContent&pageid=84
10. 使用xargs让命令读取standard input。 在linux中,除了像greb或者awk这种直接可以从standard input中读取输入处理的命令之外,大部分命令都依赖参数中设置的输入参数,丢弃standard input中的内容。比如 hostname | ping 就没有办法ping自己的主机名称因为ping并不读取hostname pipe到standard input中的内容。xargs就是用来处理这个问题,它可以build and pass standard input的内容然后invoke之后的命令,因此hostname | xargs ping就可以正确的ping自己的主机名称了。
浙公网安备 33010602011771号