计算机教育中缺失的一课: Shell
文章目录
简介
最近打算刷完MIT 的The Missing Semester of Your CS Education, 通常 Computing Ecosystem Literacy 相关的知识都是交给 CS 系的学生自己去学习, 因此这门课的目的是教给学生如何实用工具. 我会按照每个章节记录一下相关的内容.
基础
Shell 通过最基本的文字接口让我们充分使用计算机的各项功能. 这门课程使用 Bourne Again SHell(bash), 首先打开终端尝试以下命令
➜ ~ date
2020年 7月 9日 星期四 16时30分49秒 CST
➜ ~ echo hello
hello
➜ ~ echo Hello World
Hello World
空格
在 Shell 中极其重要, 它通过空格分隔参数, 例如想要访问文件夹My Photos
, 需要使用转义字符, 因此产生单引号和双引号, 其区别在于, 单引号中所有字符为字面值(不进行转义), 双引号中的$
(参数替换) 进行转义操作, 例如:
➜ Downloads mkdir "My Photos"
➜ Downloads cd My Photos
cd: string not in pwd: My
➜ Downloads cd My\ Photos
➜ My Photos cd ..
➜ Downloads cd "My Photos"
➜ My Photos ..
➜ Downloads cd 'My Photos'
➜ My Photos cd ..
➜ Downloads foo=bar
➜ Downloads echo "$foo"
bar
➜ Downloads echo '$foo'
$foo
➜ Downloads echo $foo
bar
环境变量
Shell 通过环境变量寻找data
和echo
, 环境变量为$PATH
, 可以采用which
判断某条指令所在的路径
➜ Downloads echo $PATH
/Users/lihao/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/share/dotnet:/opt/X11/bin:~/.dotnet/tools
➜ Downloads which python
/Users/lihao/anaconda3/bin/python
流和管道
>
和 <
分表表示输出流和输入流的操作, 此外>>
表示追加输出, |
表示管道操作, 他会将两个不相关的程序联系起来, 前者的输出作为后者的输入. 例如:
➜ Downloads echo hello > hello.txt
➜ Downloads cat hello.txt
hello
➜ Downloads cat < hello.txt
hello
➜ Downloads cat < hello.txt > hello2.txt
➜ Downloads cat hello2.txt
hello
➜ Downloads cat hello.txt >> hello2.txt
➜ Downloads cat hello2.txt
hello
hello
➜ Downloads ls -l / | tail -n1
lrwxr-xr-x@ 1 root admin 11 10 8 2019 var -> private/var
注意最后一条, ls
显示根目录/
下的内容, 然后教给tail -n1
输出内容的最后一条.
权限
对于某些操作需要采用sudo
, 赋予超级用户(super user) 或者(root) 权限, 在管道操作时, 由于各个操作分隔开来, 可能需要多条 sudo, 例如:
➜ Downloads sudo ls -l / | sudo tail -n2
drwxr-xr-x@ 11 root wheel 352 10 8 2019 usr
lrwxr-xr-x@ 1 root admin 11 10 8 2019 var -> private/var
Shell Scripting
脚本可以通过如下方式编写:
➜ Downloads cat mcd.sh
mcd () {
mkdir -p "$1"
cd "$1"
}
➜ Downloads source mcd.sh
➜ Downloads mcd test
➜ test cd ..
# mkdir test , cd test
$
后面可以跟一些特殊的参数, 例如
$0
表示脚本的名字, 例如在本例中, 为