missing-semester-lecture1-shell
Edited by 颍川散人 | Data: 2022.2.4 |
---|
1.Create a new directory called missing
under
/tmp
.
首先找到 /tmp
目录位置
1 | mac@192 ~ % pwd |
使用指令 cd tmp
进入 /tmp
目录下
使用指令 mkdir missing
在当前 /tmp
目录下创建新的 missing
目录
2.Look up the touch
program. The
man
program is your friend.
使用 man + 指令名称
可以跳转到指令对应的技术文档,以查阅相关用法
在这里我们使用 man touch
3.Use touch
to create a new file called
semester
in missing
.
当前在 /tmp
目录下,需要先进入 /tmp/missing
目录,然后用touch指令新建semester文件
1 | cd missing |
检查发现 /tmp/missing
下已经有了 semester
文件
4.Write the following into that file, one line at a time:
1 | #!/bin/sh |
5.The first line might be tricky to get working. It’s helpful
to know that #
starts a comment in Bash, and !
has a special meaning even within double-quoted ("
)
strings. Bash treats single-quoted strings ('
) differently:
they will do the trick in this case. See the Bash quoting
manual page for more information.
当前仍处在 /tmp/missing
目录下,直接用echo
命令和>
运算符向semester
文件中写入内容
1 | ➜ missing echo '#!/bin/sh' >semester |
其中运算符>
是重写覆盖,运算符>>
是追加内容,会自动换行
使用指令cat
来查看semester
文件内容,发现内容已经正确写入
1 | ➜ missing cat semester |
可以发现在写入第一行内容时,如果使用双引号"
而非单引号'
会报错
1 | ➜ missing echo "#!/bin/sh" > semester |
这就是提示中告诉我们的,#
和!
在双引号中也表示特殊含义,所以最好用单引号来书写内容
6.Try to execute the file, i.e. type the path to the script
(./semester
) into your shell and press enter. Understand
why it doesn’t work by consulting the output of ls
(hint:
look at the permission bits of the file).
先按照题目要求把./semester
输入到shell中,按下enter,返回错误
1 | ➜ missing ./semester |
我们根据提示关注一下文件的权限位,用ls -l 文件名
查看文件的权限位
1 | ➜ missing ls -l semester |
权限位有10位,第一位表示了文件类型,-
表示普通文件,d
表示目录
跟在后面的9位分三组,每三位一组
r表是读 (Read) 、w表示写 (Write) 、x表示执行 (Execute)
第一组表示文件拥有者的权限,第二组表示文件所属组拥有的权限,最后一组表示其他用户拥有的权限
可见,该文件无法被执行
7.Run the command by explicitly starting the sh
interpreter, and giving it the file semester
as the first
argument, i.e. sh semester
. Why does this work, while
./semester
didn’t?
直接输入命令sh semester
按下回车运行,可见脚本文件成功执行
sh
命令是运行Linux或macOS脚本文件的,解析脚本的操作和执行文件不同,因为semester
不是可执行文件,所以./semester
无法运行而sh
可以
8.Look up the chmod
program (e.g. use
man chmod
).
输入命令man chmod
查看chmod
9.Use chmod
to make it possible to run the
command ./semester
rather than having to type
sh semester
. How does your shell know that the file is
supposed to be interpreted using sh
? See this page on the
shebang line
for more information
由上述操作可知因为semester
文件缺少可执行权限而无法被直接运行,用chmod
命令可以为其增加可执行权限
使用以下指令
1 | ➜ missing chmod u+x semester |
该指令为user增加可执行权限,使用ls
查看权限,发现确实增加了可执行权限
1 | ➜ missing ls -l semester |
再次输入./semester
发现脚本文件可以被顺利执行
10.Use |
and >
to write the
“last modified” date output by semester
into a file called
last-modified.txt
in your home directory.
|
指令可以把|
左边的输出作为右边的输入,比如这个指令ls -l / | tail -n1
,就是把ls -l /
的输出结果作为tail -n1
的输入,最终输出主目录信息的最后一行
就这一问,首先要获取./semester
输出内容的第四行,也就是last-modified
的内容
想获取文件指定行的内容,可以用指令tail -n+k filename | head -n1
,该指令先获取文件从第k行以后的内容,然后输出该内容的第一行,也就是原文件的第k行
所以可以用以下指令完成题目要求
1 | ➜ missing ./semester | tail -n+4 | head -n1 | >last-modified.txt |