Course
Notes on The Missing Semester: II. Shell Tools and Scripting
These are study notes for `Notes on The Missing Semester: II. Shell Tools and Scripting`, using the 5R note-taking method to deepen understanding of the course knowledge points and learning takeaways.
On this page
Record
Shell Scripts
Shell characteristics: Most shells have their own scripting language, including variables, control flow, and their own syntax. Shell scripts differ from other scripting languages in that they are optimized for the work shells do. Therefore, creating command pipelines, saving results to files, and reading input from standard input are native operations in shell scripts, making them easier to use than general-purpose scripting languages.
bash scripts: In bash, the syntax for assigning a value to a variable is
foo=bar, and the syntax for accessing the value stored in a variable is$foo. Note thatfoo = bar(with spaces) will not work correctly, because the interpreter will call the programfooand pass=andbaras arguments. Strings in Bash are defined with the delimiters'and", but their meanings are different. A string defined with'is a literal string, in which variables are not expanded, while a string defined with"substitutes variable values.bashalso supports control-flow keywords such asif,case,while, andfor. Similarly,bashalso supports functions, which can accept arguments and operate based on those arguments.Bash special variables: See the complete list here. -
$0- Script name -$1to$9- Arguments to the script.$1is the first argument, and so on. -$@- All arguments -$#- Number of arguments -$?- Return value of the previous command -$$- Process ID of the current script -!!- The complete previous command, including arguments. Common use: when a command fails due to insufficient permissions, you can retry withsudo !!. -$_- The last argument of the previous command. If you are using an interactive shell, you can get this value by pressingEscand then typing .Short-circuit operators (short-circuiting): Commands usually return output via
STDOUTand errors plus error codes viaSTDERR, making it easier for scripts to report errors in a friendly way. Return codes, or exit statuses, are how scripts/commands communicate execution state. A return value of 0 means successful execution; every other non-0 return value means an error occurred. Exit codes can be used with&&(AND operator) and||(OR operator) to perform conditional logic and decide whether to execute other programs. They are both short-circuit operators (short-circuiting). Multiple commands on the same line can be separated with;. The programtruealways has return code0, andfalsealways has return code1.Command substitution: When you use a form like
$( CMD )to execute the commandCMD, its output replaces$( CMD ). For example, if you runfor file in $(ls), the shell first callsls, then iterates over the returned values. There is also a lesser-known similar feature called process substitution:<( CMD )executesCMD, outputs the result to a temporary file, and replaces<( CMD )with the temporary filename. This is useful when we want return values to be passed through a file rather than STDIN. For example,diff <(ls foo) <(ls bar)shows the differences between the files in the foldersfooandbar.
Shell Tools
Learning how to use commands: The most common method is to add the
-hor--helpflag to the corresponding command line. Another, more detailed method is to use themancommand. Themancommand is short for manual, and it provides user manuals for commands. Sometimes manuals are so detailed that it is hard to find the most common flags and syntax. TLDR pages are a good alternative: they provide examples that can help you quickly find the right options.Finding files: All UNIX-like systems include a tool named
find, which is an excellent shell tool for finding files. Thefindcommand recursively searches for files that meet specified criteria. In addition to listing the files found, find can also perform operations on all files it finds.fdis a simpler, faster, and friendlier program that can serve as an alternative tofind. It has many good default settings, such as colored output, regular-expression matching by default, Unicode support, and, in my view, more intuitive syntax. The syntax for searching with the patternPATTERNisfd PATTERN.locateuses a database updated byupdatedb; on most systems,updatedbis updated daily bycron. This requires a tradeoff between speed and freshness. Also,findand similar tools can search by other attributes such as file size, modification time, or permissions, whilelocatecan only search by filename. Here is a more detailed comparison.Finding code: The
grepcommand has many options, which makes it a very versatile tool. The ones I often use include-C, which gets the context of search results, and-v, which inverts the results, that is, outputs results that do not match. For example,grep -C 5prints five lines before and after each match. When you need to search a large number of files, use-Rto recursively enter subdirectories and search all text files.Finding shell commands: The
historycommand lets you access the history of commands entered in the shell in a programmer-friendly way. This command prints the commands in the shell history to standard output. If we want to search history, we can use a pipe to pass the output togrepfor pattern searching.history | grep findprints commands containing the substring find. You can useCtrl+Rto search command history backward. After typingCtrl+R, you can enter a substring to match and find historical command lines.Directory navigation: Use the tools
fasdand autojump to find the most frequently or recently used files and directories. Fasd ranks files and directories based on frecency, meaning it sorts by both frequency and recency. By default,fasduses the commandzto help us quickly switch to the most frequently visited directories.
Reduce
Shell scripts include variables, control flow, and their own syntax
bashsupports control-flow keywords such asif,case,while, andforShell tool commands:
man,find,grep,fasd
Recite
Shell scripting languages include variables, control flow, and their own syntax, and Bash is one scripting language.
Bash scripts contain special variables, such as
$0,$1,$@,$?, and so on; they also support control-flow keywords such asif,case,while, andfor, and have their own syntax features, such as leaving no spaces in assignments (foo=bar), while the'and"delimiters indicate literal strings and expanded strings respectively.Tool commands in the shell can conveniently provide the following functions: viewing command help, finding files, finding code, searching historical shell commands, directory navigation, and many more.
Recommended commands to master:
man(view command syntax),find(find files),grep(find file contents, namely code),fasd(quickly switch to frequently used directories)
Reflect
This chapter still focuses on foundational knowledge, and the core is still mastering basic commands:
1. Detailed explanation of the man command
View command help in Linux
Additional Notes
The man command is a help command on Linux. Through the man command, you can view help information for Linux commands, configuration files, programming, and more.
Syntax
man(选项)(参数)Options
-a:在所有的man帮助手册中搜索;
-f:等价于whatis指令,显示给定关键字的简短描述信息;
-P:指定内容时使用分页程序;
-M:指定man手册搜索的路径。Arguments
- Number: specifies which man manual section to search for help in;
- Keyword: specifies the keyword to search for help.
What the Numbers Represent
1:用户在shell环境可操作的命令或执行文件;
2:系统内核可调用的函数与工具等
3:一些常用的函数(function)与函数库(library),大部分为C的函数库(libc)
4:设备文件说明,通常在/dev下的文件
5:配置文件或某些文件格式
6:游戏(games)
7:惯例与协议等,如Linux文件系统,网络协议,ASCII code等说明
8:系统管理员可用的管理命令
9:跟kernel有关的文件Examples
When we enter man ls, it displays “LS(1)” in the upper-left corner. Here, “LS” indicates the manual name, while “(1)” indicates that this manual is in section 1. Similarly, when we enter man ifconfig, it displays “IFCONFIG(8)” in the upper-left corner. You can also enter the command as: “man [section number] manual name”.
man searches in the order of manual section numbers, for example:
man sleepThis will only display the manual for the sleep command. If you want to view the library function sleep, enter:
man 3 sleepRelated Commands
tldr: A simplified manual. Unlike man, it does not list all usage parameters and explanations; it only shows a few commonly used samples and explanations- Open-source address: https://github.com/tldr-pages/tldr/
- Official website: https://tldr.sh/
- Online version: https://tldr.ostera.io/
2. Detailed explanation of the find command
Find files under a specified directory
Additional Notes
The find command is used to find files under a specified directory. Any string before the arguments is treated as the directory name to search. If no arguments are set when using this command, the find command searches for subdirectories and files under the current directory, and displays all subdirectories and files it finds.
Syntax
find(选项)(参数)Options
-amin<分钟>:查找在指定时间曾被存取过的文件或目录,单位以分钟计算;
-anewer<参考文件或目录>:查找其存取时间较指定文件或目录的存取时间更接近现在的文件或目录;
-atime<24小时数>:查找在指定时间曾被存取过的文件或目录,单位以24小时计算;
-cmin<分钟>:查找在指定时间之时被更改过的文件或目录;
-cnewer<参考文件或目录>查找其更改时间较指定文件或目录的更改时间更接近现在的文件或目录;
-ctime<24小时数>:查找在指定时间之时被更改的文件或目录,单位以24小时计算;
-daystart:从本日开始计算时间;
-depth:从指定目录下最深层的子目录开始查找;
-empty:寻找文件大小为0 Byte的文件,或目录下没有任何子目录或文件的空目录;
-exec<执行指令>:假设find指令的回传值为True,就执行该指令;
-false:将find指令的回传值皆设为False;
-fls<列表文件>:此参数的效果和指定“-ls”参数类似,但会把结果保存为指定的列表文件;
-follow:排除符号连接;
-fprint<列表文件>:此参数的效果和指定“-print”参数类似,但会把结果保存成指定的列表文件;
-fprint0<列表文件>:此参数的效果和指定“-print0”参数类似,但会把结果保存成指定的列表文件;
-fprintf<列表文件><输出格式>:此参数的效果和指定“-printf”参数类似,但会把结果保存成指定的列表文件;
-fstype<文件系统类型>:只寻找该文件系统类型下的文件或目录;
-gid<群组识别码>:查找符合指定之群组识别码的文件或目录;
-group<群组名称>:查找符合指定之群组名称的文件或目录;
-help或--help:在线帮助;
-ilname<范本样式>:此参数的效果和指定“-lname”参数类似,但忽略字符大小写的差别;
-iname<范本样式>:此参数的效果和指定“-name”参数类似,但忽略字符大小写的差别;
-inum<inode编号>:查找符合指定的inode编号的文件或目录;
-ipath<范本样式>:此参数的效果和指定“-path”参数类似,但忽略字符大小写的差别;
-iregex<范本样式>:此参数的效果和指定“-regexe”参数类似,但忽略字符大小写的差别;
-links<连接数目>:查找符合指定的硬连接数目的文件或目录;
-lname<范本样式>:指定字符串作为寻找符号连接的范本样式;
-ls:假设find指令的回传值为True,就将文件或目录名称列出到标准输出;
-maxdepth<目录层级>:设置最大目录层级;
-mindepth<目录层级>:设置最小目录层级;
-mmin<分钟>:查找在指定时间曾被更改过的文件或目录,单位以分钟计算;
-mount:此参数的效果和指定“-xdev”相同;
-mtime<24小时数>:查找在指定时间曾被更改过的文件或目录,单位以24小时计算;
-name<范本样式>:指定字符串作为寻找文件或目录的范本样式;
-newer<参考文件或目录>:查找其更改时间较指定文件或目录的更改时间更接近现在的文件或目录;
-nogroup:找出不属于本地主机群组识别码的文件或目录;
-noleaf:不去考虑目录至少需拥有两个硬连接存在;
-nouser:找出不属于本地主机用户识别码的文件或目录;
-ok<执行指令>:此参数的效果和指定“-exec”类似,但在执行指令之前会先询问用户,若回答“y”或“Y”,则放弃执行命令;
-path<范本样式>:指定字符串作为寻找目录的范本样式;
-perm<权限数值>:查找符合指定的权限数值的文件或目录;
-print:假设find指令的回传值为True,就将文件或目录名称列出到标准输出。格式为每列一个名称,每个名称前皆有“./”字符串;
-print0:假设find指令的回传值为True,就将文件或目录名称列出到标准输出。格式为全部的名称皆在同一行;
-printf<输出格式>:假设find指令的回传值为True,就将文件或目录名称列出到标准输出。格式可以自行指定;
-prune:不寻找字符串作为寻找文件或目录的范本样式;
-regex<范本样式>:指定字符串作为寻找文件或目录的范本样式;
-size<文件大小>:查找符合指定的文件大小的文件;
-true:将find指令的回传值皆设为True;
-type<文件类型>:只寻找符合指定的文件类型的文件;
-uid<用户识别码>:查找符合指定的用户识别码的文件或目录;
-used<日数>:查找文件或目录被更改之后在指定时间曾被存取过的文件或目录,单位以日计算;
-user<拥有者名称>:查找符和指定的拥有者名称的文件或目录;
-version或——version:显示版本信息;
-xdev:将范围局限在先行的文件系统中;
-xtype<文件类型>:此参数的效果和指定“-type”参数类似,差别在于它针对符号连接检查。Arguments
Starting directory: the starting directory for finding files.
Examples
# 当前目录搜索所有文件,文件内容 包含 “140.206.111.111” 的内容
find . -type f -name "*" | xargs grep "140.206.111.111"Matching by file or regular expression
List all files and folders under the current directory and its subdirectories
find .Find filenames ending in .txt under the /home directory
find /home -name "*.txt"Same as above, but ignore case
find /home -iname "*.txt"Find all files ending in .txt and .pdf under the current directory and its subdirectories
find . \( -name "*.txt" -o -name "*.pdf" \)
或
find . -name "*.txt" -o -name "*.pdf"Match file paths or files
find /usr/ -path "*local*"Match file paths based on regular expressions
find . -regex ".*\(\.txt\|\.pdf\)$"Same as above, but ignore case
find . -iregex ".*\(\.txt\|\.pdf\)$"Negated arguments
Find files under /home that do not end in .txt
find /home ! -name "*.txt"Search by file type
find . -type 类型参数Type argument list:
- f regular file
- l symbolic link
- d directory
- c character device
- b block device
- s socket
- p Fifo
Search based on directory depth
Limit the maximum downward depth to 3
find . -maxdepth 3 -type fSearch for all files at least 2 subdirectories deep from the current directory
find . -mindepth 2 -type fSearch by file timestamp
find . -type f 时间戳Every file in a UNIX/Linux file system has three timestamps:
- Access time (-atime/days, -amin/minutes): the user’s most recent access time.
- Modification time (-mtime/days, -mmin/minutes): the last time the file was modified.
- Change time (-ctime/days, -cmin/minutes): the last time file metadata (such as permissions) was modified.
Search for all files accessed within the last seven days
find . -type f -atime -7Search for all files accessed exactly seven days ago
find . -type f -atime 7Search for all files accessed more than seven days ago
find . -type f -atime +7Search for all files whose access time is more than 10 minutes ago
find . -type f -amin +10Find all files newer than file.log by modification time
find . -type f -newer file.logMatch by file size
find . -type f -size 文件大小单元File size units:
- b — blocks (512 bytes)
- c — bytes
- w — words (2 bytes)
- k — kilobytes
- M — megabytes
- G — gigabytes
Search for files larger than 10KB
find . -type f -size +10kSearch for files smaller than 10KB
find . -type f -size -10kSearch for files equal to 10KB
find . -type f -size 10kDelete matching files
Delete all .txt files under the current directory
find . -type f -name "*.txt" -deleteMatch by file permissions/ownership
Search for files with permission mode 777 under the current directory
find . -type f -perm 777Find php files under the current directory whose permissions are not mode 644
find . -type f -name "*.php" ! -perm 644Find all files owned by user tom under the current directory
find . -type f -user tomFind all files owned by group sunk under the current directory
find . -type f -group sunkCombine with other commands using the -exec option
Find all root-owned files under the current directory and change ownership to user tom
find .-type f -user root -exec chown tom {} \;In the example above, {} is used together with the -exec option to match all files, then it is replaced with the corresponding filename.
Find and delete all .txt files under your home directory
find $HOME/. -name "*.txt" -ok rm {} \;In the example above, -ok behaves the same as -exec, but it prompts you before executing the corresponding operation.
Find all .txt files under the current directory and concatenate them into the all.txt file
find . -type f -name "*.txt" -exec cat {} \;> /all.txtMove .log files older than 30 days into the old directory
find . -type f -mtime +30 -name "*.log" -exec cp {} old \;Find all .txt files under the current directory and print them in the form “File: filename”
find . -type f -name "*.txt" -exec printf "File: %s\n" {} \;Because multiple commands cannot be used in the -exec argument of a single-line command, the following method can accept multiple commands after -exec
-exec ./text.sh {} \;Search while skipping specified directories
Find all .txt files under the current directory or its subdirectories, but skip the subdirectory sk
find . -path "./sk" -prune -o -name "*.txt" -print⚠️ ./sk cannot be written as ./sk/, otherwise it will have no effect.
Ignore two directories
find . \( -path ./sk -o -path ./st \) -prune -o -name "*.txt" -print⚠️ If you write a relative path, you must add ./
Collection of other find tips
To list all zero-length files
find . -emptyOther examples
find ~ -name '*jpg' # 主目录中找到所有的 jpg 文件。 -name 参数允许你将结果限制为与给定模式匹配的文件。
find ~ -iname '*jpg' # -iname 就像 -name,但是不区分大小写
find ~ ( -iname 'jpeg' -o -iname 'jpg' ) # 一些图片可能是 .jpeg 扩展名。幸运的是,我们可以将模式用“或”(表示为 -o)来组合。
find ~ \( -iname '*jpeg' -o -iname '*jpg' \) -type f # 如果你有一些以 jpg 结尾的目录呢? (为什么你要命名一个 bucketofjpg 而不是 pictures 的目录就超出了本文的范围。)我们使用 -type 参数修改我们的命令来查找文件。
find ~ \( -iname '*jpeg' -o -iname '*jpg' \) -type d # 也许你想找到那些命名奇怪的目录,以便稍后重命名它们I have taken a lot of photos recently, so let’s narrow it down to files changed last week
find ~ \( -iname '*jpeg' -o -iname '*jpg' \) -type f -mtime -7You can filter by file status change time (ctime), modification time (mtime), or access time (atime). These are in days, so if you want finer-grained control, you can express them in minutes (cmin, mmin, and amin, respectively). Unless you know exactly what time you want, you will probably put a number after + (greater than) or - (less than).
But perhaps you do not care about your photos. Maybe you are running out of disk space, so you want to find all huge files (let’s define “huge” as “greater than 1GB”) under the log directory:
find /var/log -size +1GOr perhaps you want to find all files owned by bcotton in /data:
find /data -owner bcottonYou can also find files by permissions. Maybe you want to find files in your home directory that are readable by everyone, to make sure you are not oversharing.
find ~ -perm -o=rDelete automatically generated files on Mac
find ./ -name '__MACOSX' -depth -exec rm -rf {} \;Count lines of code
find . -name "*.java"|xargs cat|grep -v ^$|wc -l # 代码行数统计, 排除空行3. Detailed explanation of the grep command
A powerful text search tool
Additional Notes
grep (global search regular expression(RE) and print out the line, globally search regular expressions and print the lines) is a powerful text search tool. It can use regular expressions to search text and print matching lines. It is used for filtering/searching specific characters. Regular expressions can be used together with many commands, making it very flexible in use.
Options
-a --text # 不要忽略二进制数据。
-A <显示行数> --after-context=<显示行数> # 除了显示符合范本样式的那一行之外,并显示该行之后的内容。
-b --byte-offset # 在显示符合范本样式的那一行之外,并显示该行之前的内容。
-B<显示行数> --before-context=<显示行数> # 除了显示符合样式的那一行之外,并显示该行之前的内容。
-c --count # 计算符合范本样式的列数。
-C<显示行数> --context=<显示行数>或-<显示行数> # 除了显示符合范本样式的那一列之外,并显示该列之前后的内容。
-d<进行动作> --directories=<动作> # 当指定要查找的是目录而非文件时,必须使用这项参数,否则grep命令将回报信息并停止动作。
-e<范本样式> --regexp=<范本样式> # 指定字符串作为查找文件内容的范本样式。
-E --extended-regexp # 将范本样式为延伸的普通表示法来使用,意味着使用能使用扩展正则表达式。
-f<范本文件> --file=<规则文件> # 指定范本文件,其内容有一个或多个范本样式,让grep查找符合范本条件的文件内容,格式为每一列的范本样式。
-F --fixed-regexp # 将范本样式视为固定字符串的列表。
-G --basic-regexp # 将范本样式视为普通的表示法来使用。
-h --no-filename # 在显示符合范本样式的那一列之前,不标示该列所属的文件名称。
-H --with-filename # 在显示符合范本样式的那一列之前,标示该列的文件名称。
-i --ignore-case # 忽略字符大小写的差别。
-l --file-with-matches # 列出文件内容符合指定的范本样式的文件名称。
-L --files-without-match # 列出文件内容不符合指定的范本样式的文件名称。
-n --line-number # 在显示符合范本样式的那一列之前,标示出该列的编号。
-P --perl-regexp # PATTERN 是一个 Perl 正则表达式
-q --quiet或--silent # 不显示任何信息。
-R/-r --recursive # 此参数的效果和指定“-d recurse”参数相同。
-s --no-messages # 不显示错误信息。
-v --revert-match # 反转查找。
-V --version # 显示版本信息。
-w --word-regexp # 只显示全字符合的列。
-x --line-regexp # 只显示全列符合的列。
-y # 此参数效果跟“-i”相同。
-o # 只输出文件中匹配到的部分。
-m <num> --max-count=<num> # 找到num行结果后停止查找,用来限制匹配行数Regular Expressions
^ # 锚定行的开始 如:'^grep'匹配所有以grep开头的行。
$ # 锚定行的结束 如:'grep$' 匹配所有以grep结尾的行。
. # 匹配一个非换行符的字符 如:'gr.p'匹配gr后接一个任意字符,然后是p。
* # 匹配零个或多个先前字符 如:'*grep'匹配所有一个或多个空格后紧跟grep的行。
.* # 一起用代表任意字符。
[] # 匹配一个指定范围内的字符,如'[Gg]rep'匹配Grep和grep。
[^] # 匹配一个不在指定范围内的字符,如:'[^A-Z]rep' 匹配不包含 A-Z 中的字母开头,紧跟 rep 的行
\(..\) # 标记匹配字符,如'\(love\)',love被标记为1。
\< # 锚定单词的开始,如:'\<grep'匹配包含以grep开头的单词的行。
\> # 锚定单词的结束,如'grep\>'匹配包含以grep结尾的单词的行。
x\{m\} # 重复字符x,m次,如:'0\{5\}'匹配包含5个o的行。
x\{m,\} # 重复字符x,至少m次,如:'o\{5,\}'匹配至少有5个o的行。
x\{m,n\} # 重复字符x,至少m次,不多于n次,如:'o\{5,10\}'匹配5--10个o的行。
\w # 匹配文字和数字字符,也就是[A-Za-z0-9],如:'G\w*p'匹配以G后跟零个或多个文字或数字字符,然后是p。
\W # \w的反置形式,匹配一个或多个非单词字符,如点号句号等。
\b # 单词锁定符,如: '\bgrep\b'只匹配grep。 Common uses of the grep command
Search for a word in a file; the command returns text lines containing “match_pattern”:
grep match_pattern file_name
grep "match_pattern" file_nameSearch in multiple files:
grep "match_pattern" file_1 file_2 file_3 ...Output all lines except matching ones using the -v option:
grep -v "match_pattern" file_nameHighlight matches with color using the –color=auto option:
grep "match_pattern" file_name --color=autoUse regular expressions with the -E option:
grep -E "[1-9]+"
# 或
egrep "[1-9]+"Use regular expressions with the -P option:
grep -P "(\d{3}\-){2}\d{4}" file_nameOnly output the matched part of the file using the -o option:
echo this is a test line. | grep -o -E "[a-z]+\."
line.
echo this is a test line. | egrep -o "[a-z]+\."
line.Count the number of lines containing the matching string in a file or text using the -c option:
grep -c "text" file_nameSearch command-line history for records where the git command was entered:
history | grep gitOutput line numbers for lines containing the matching string using the -n option:
grep "text" -n file_name
# 或
cat file_name | grep "text" -n
#多个文件
grep "text" -n file_1 file_2Print the character or byte offset where the pattern match is located:
echo gun is not unix | grep -b -o "not"
7:not
#一行中字符串的字符偏移是从该行的第一个字符开始计算,起始值为0。选项 **-b -o** 一般总是配合使用。Search multiple files and find which files contain matching text:
grep -l "text" file1 file2 file3...Recursive grep file search
Recursively search text in multi-level directories:
grep "text" . -r -n
# .表示当前目录。Ignore case in the matching pattern:
echo "hello world" | grep -i "HELLO"
# helloThe -e option specifies multiple matching patterns:
echo this is a text line | grep -e "is" -e "line" -o
is
is
line
#也可以使用 **-f** 选项来匹配多个样式,在样式文件中逐行写出需要匹配的字符。
cat patfile
aaa
bbb
echo aaa bbb ccc ddd eee | grep -f patfile -oInclude or exclude specified files in grep search results:
# 只在目录中所有的.php和.html文件中递归搜索字符"main()"
grep "main()" . -r --include *.{php,html}
# 在搜索结果中排除所有README文件
grep "main()" . -r --exclude "README"
# 在搜索结果中排除filelist文件列表里的文件
grep "main()" . -r --exclude-from filelistUse grep with a 0-byte suffix and xargs:
# 测试文件:
echo "aaa" > file1
echo "bbb" > file2
echo "aaa" > file3
grep "aaa" file* -lZ | xargs -0 rm
# 执行后会删除file1和file3,grep输出用-Z选项来指定以0值字节作为终结符文件名(\0),xargs -0 读取输入并用0值字节终结符分隔文件名,然后删除匹配文件,-Z通常和-l结合使用。Silent grep output:
grep -q "test" filename
# 不会输出任何信息,如果命令运行成功返回0,失败则返回非0值。一般用于条件测试。Print lines before or after matching text:
# 显示匹配某个结果之后的3行,使用 -A 选项:
seq 10 | grep "5" -A 3
5
6
7
8
# 显示匹配某个结果之前的3行,使用 -B 选项:
seq 10 | grep "5" -B 3
2
3
4
5
# 显示匹配某个结果的前三行和后三行,使用 -C 选项:
seq 10 | grep "5" -C 3
2
3
4
5
6
7
8
# 如果匹配结果有多个,会用“--”作为各匹配结果之间的分隔符:
echo -e "a\nb\nc\na\nb\nc" | grep a -A 1
a
b
--
a
b4. Detailed explanation of the fasd command
Temporarily unavailable.
Review
MIT is MIT; I searched for the fasd command mentioned by the teaching assistant for ages and could not find it.
- Master the
findandgrepcommands - Understand the meaning of special variables and control-flow statements
- Complete the after-class exercises and try writing things by hand