Lecture2: Shell and useful tools
[^Asides]: 弹幕精辟的总结了咖喱味以后,啃了两天才啃下硬骨头,后半部分的useful tools目前实战性不是很强,但多少需要学以致用。
Shell
依我个人的理解,shell充当kernel和user之间communicate的桥梁,bash是一种scripting languages。
学习shell,学习脚本语言,更好的提高计算机作为一种工具对人类自动化的作用。
将命令行的输出(output of cmdline)当作变量
1
2
3foo = $(pwd)
#pwd是一种命令,pwd的输出是当前的working directories,这里将pwd的输出当作变量的值赋给foo;
echo "We are in $(pwd)"可以在个人电脑的terminal中输入如上命令,体会输入结果。
同时,这里也需要注意bash 的单双引号之间的区别。
1
2
3
4foo = bar
echo 'This is foo'
echo "This is bar"
echo "This is $(foo)"流程替换
1
2
3cat <(ls) <(ls ..)
#mind the blankspaces,and always mind the blankspaces in shell
#起到了串联工作区的作用更改拓展
ls *.sh
Convert image.{png,jpg} ##这里会有automatically expansion
touch foo{,1,2,10} ##同样也是automatically expansion
touch {foo,bar}/{a…j}
这里以笛卡儿积的形式理解,即创建fooa,foob,fooc,…,bara,barb,…(其中a,b,…,j是foo,bar下的内容)
有时,bash在处理某些人无伤可能不是那么好用,可以自己写脚本与shell实现很多的交互。
python script:
1
2#import sys
##这是为了防止在某些情况下,python有时不尝试进行与shell的交互,增强了代码的可移植性。如何make it to be executable from the shell?(portability up?)
1
2
3
4#可以在代码块的前端添加代码,使用shebang符号
!/usr/Local/bin/python
#This helps the shell to know why should the file be interpreted as python and how to interpret the code file as python使用PATH variable[refer to lecture1]
1
2!/usr/bin/env python
#将在该路径中搜索我们在编译的时候需要使用的python library
/usr/bin这个目录下放置了很多binary files,env 这个命令的使用,使我们use the binary file to interpret file
bash很难debug:Shellcheck工具(github)
‘#!’符号:shebang
It is a good practice [代码规范] to write shebang lines using the env cmd that will resolve to whatever command lives in the system.
在不同的机器上,有效的命令行往往彼此之前有很大的不同,如果想增强脚本语言的可移植性,就要养成良好的代码规范。
Last 4 tips kept in mind
[^Asides]: 诚实的说,目前还没有理解,可以对照官方lecture notes更好的理解。