[笔记]The Linux command line
Notes on The Linux Command Line (by W. E. Shotts Jr.)
edited by Gopher
感觉博客园是不是搞了什么CSS在里头……在博客园显示效果挺蛋疼的。。。这本书相当棒,建议一读
File, file systems and commands
ls-a(all) -d(directory) -h(human-readable)
less(show file content)FHS
/bin: Contains binaries (programs) that must be present for the system to boot and run.
/boot: Contains the Linux kernel, initial RAM disk image (for drivers needed at boot time), and the boot loader.
boot/grub/grub.confor menu.lst, which are used to configure the boot loader
/boot/vmlinuz, the Linux kernel/dev: Device nodes
/etc: The
/etcdirectory contains all of the system-wide configuration files. It also contains a collection of shell scripts which start each of the system services at boot time. Everything in this directory should be readable text./home: Ordinary users can only write files in their home directories
/lib: Shared library files.
/lost+found
/mnt
/opt: This is mainly used to hold commercial software products that may be installed on your system.
/proc
/root
/sbin: This directory contains “system” binaries. These are programs that perform vital system tasks that are generally reserved for the superuser.
/tmp
/usr: Unix software resources. It contains all the programs and support files used by regular users.
/usr/bincontains the executable programs installed by your Linux distribution. Shared libraries of programs contained in it are stored in/usr/lib.The
/usr/localtree is where programs that are not included with your distribution but are intended for system-wide use are installed. Programs compiled from source code are normally installed in/usr/local/bin./usr/sbincontains more system administration programs./var
/var/logrecords of various system activityWildcards
| Wildcard | Meeaning |
|---|---|
| * | Matches any characters |
| ? | Matches any single character |
| \ [characters] | Matches any character that is a member of the set characters |
| [!characters] | Matches any character that is not a member of the set characters |
| [[:class:]] | Matches any character that is a member of the specified class |
Commonly used character classes
| Character class | Meaning |
|---|---|
| [:alnum:] | Matches any alphanumeric character |
| [:alpha:] | Matches any alphabetic character |
| [:digit:] | Matches any numeral |
| [:lower:] | Matches any lowercase letter |
| [:upper:] | Matches any uppercase letter |
cp
-a(--archive, copy with attributes) -u(--update, update only -- do not override)
Be careful with
rm!lsfirst before yourm -rf.ln
-s(soft/symbolic link)

Something with command
- type – Indicate how a command name is interpreted
- which – Display which executable program will be executed
- help – Get help for shell builtins
- man – Display a command's manual page
- apropos – Display a list of appropriate commands
- info – Display a command's info entry
- whatis – Display a very brief description of a command
- alias – Create an alias for a command
To learn more about Steve Bourne, father of the Bourne Shell, see this Wikipedia
article:
http://en.wikipedia.org/wiki/Steve_Bourne
Here is an article about the concept of shells in computing:
http://en.wikipedia.org/wiki/Shell_\(computing\)
The full version of the Linux Filesystem Hierarchy Standard can be found here:
http://www.pathname.com/fhs/
An article about the directory structure of Unix and Unix-like systems:
http://en.wikipedia.org/wiki/Unix_directory_structure
A detailed description of the ASCII text format:
http://en.wikipedia.org/wiki/ASCII
The Bash Reference Manual is a reference guide to the bash shell. It’s still a ref-
erence work but contains examples and is easier to read than the bash man page.
http://www.gnu.org/software/bash/manual/bashref.html
The Bash FAQ contains answers to frequently asked questions regarding bash.
This list is aimed at intermediate to advanced users, but contains a lot of good in-
formation.
http://mywiki.wooledge.org/BashFAQ
The GNU Project provides extensive documentation for its programs, which form
the core of the Linux command line experience. You can see a complete list here:
http://www.gnu.org/manual/manual.html
Wikipedia has an interesting article on man pages:
http://en.wikipedia.org/wiki/Man_page
A discussion of symbolic links:
http://en.wikipedia.org/wiki/Symbolic_link
Redirection
- Commands
- cat - Concatenate files
- sort - Sort lines of text
- uniq - Report or omit repeated lines
- grep - Print lines matching a pattern
- wc - Print newline, word, and byte counts for each file
- head - Output the first part of a file
- tail - Output the last part of a file
tee - Read from standard input and write to standard output and files
>:truncate / redirect stdout
2>: redirect stderr
2>&1: redirect stderr to (redirected) stdout
&>: redirect both stderr and stdout
&>>: redirect with append
2> /dev/null: redirect stderr to bit bucket (supress stderr)
The redirection operator silently creates or overwrites files, so you need to treat it with a lot of respect
e.g. (this will override/destroyless)
cd /usr/bin
ls > less
Shell basics and terminal keystrokes
~(tilde) = /home/user_nameArithmetic expansion:
$((expression))(/divide into integers,**exponentiation,()should contains expressions like$(())){}expands ranges. e.g.{1-2000}-{a-z}Parameter expansion:
printenv,$envCommand substitution:
command1 $(command2)orcommand1 `command2`Quoting:
""expand expression (treats space as space, e.g., tryecho $(cal)andecho "$(cal)")
''treat literally
\escape carriage return
/espace special charactersKeystrokes (Emacs style)
| Key | Meaning |
|---|---|
| Ctrl-a | Move cursor to the beginning of the line. |
| Ctrl-e | Move cursor to the end of the line. |
| Ctrl-f | Move cursor forward one character; same as the right arrow key. |
| Ctrl-b | Move cursor backward one character; same as the left arrow key. |
| Alt-f | Move cursor forward one word. |
| Alt-b | Move cursor backward one word. |
| Ctrl-l | Clear the screen and move the cursor to the top left corner. The clear command does the same thing. |
| Ctrl-d | Delete the character at the cursor location |
| Ctrl-t | Transpose (exchange) the character at the cursor location with the one preceding it. |
| Alt-t | Transpose the word at the cursor location with the one preceding it. |
| Alt-l | Convert the characters from the cursor location to the end of the word to lowercase. |
| Alt-u | Convert the characters from the cursor location to the end of the word to uppercase. |
| Ctrl-k | Kill text from the cursor location to the end of line. |
| Ctrl-u | Kill text from the cursor location to the beginning of the line. |
| Alt-Backspace | Kill text from the cursor location to the beginning of the current word. If the cursor is at the beginning of a word, kill the previous word. |
| Ctrl-y | Yank text from the kill-ring and insert it at the cursor location. |
history: C-r (Reverse incremental search.)
The bash man page has major sections on both expansion and quoting which cover these topics in a more formal manner.
The Bash Reference Manual also contains chapters on expansion and quoting:
http://www.gnu.org/software/bash/manual/bashref.html
The Wikipedia has a good article on computer terminals:
http://en.wikipedia.org/wiki/Computer_terminal
Permission and process
su– Run a shell with substitute user and group IDs
sudo– Execute a command as another userr (4) w (2) x (1); u(user) o(other) g(group)
File types:
| Type | Meaning |
|---|---|
| c | A character special file. This file type refers to a device that handles data as a stream of bytes, such as a terminal or modem. |
| b | A block special file. This file type refers to a device that handlesdata in blocks, such as a hard drive or CD-ROM drive. |
| l | A symbolic link. Notice that with symbolic links, the remaining file attributes are always “rwxrwxrwx” and are dummy values. The real file attributes are those of the file the symbolic link points to |
| 4. | Attribute | Files |
|---|---|---|
| r | Allows a file to be opened and read. | Allows a directory's contents to be listed if the execute attribute is also set. |
| w | Allows a file to be written to or truncated, however this attribute does not allow files to be renamed or deleted. The ability to delete or rename files is determined by directory attributes. | Allows files within a directory to be created, deleted, and renamed if the execute attribute is also set. |
| x | Allows a file to be treated as a program and executed. Program files written in scripting languages must also be set as readable to be executed. | Allows a directory to be entered, e.g., cd directory. |
Special permissions:
setuid(4000 or u+s): When applied to an executable file, it sets the effective user ID from that of the real user (the user actually running the program) to that of the program's owner. e.g. let a program runs as root.setgid(2000 or g+s): changes the effective group ID from the real group ID of the real user to that
of the file owner. If the setgid bit is set on a directory, newly created files in the directory will be given the group ownership of the directory rather the group ownership of the file's creator. This is useful in a shared directory when members of a common group need access to all the files in the directory, regardless of the file owner's primary group.sticky(1000 or +t): If applied to a directory, it prevents users from deleting or renaming files unless the user is either the owner of the directory, the owner of the file, or the superuser. This is often used to control access to a shared directory, such as/tmp.su: -l(or -, get login shell, default to root); -c(single command)chown: (user):(group)Process
ps – Report a snapshot of current processes (ps aux)
top – Display tasks
jobs – List active jobs
bg – Place a job in the background
fg – Place a job in the foreground
kill – Send a signal to a process
killall – Kill processes by name
shutdown – Shutdown or reboot the systemProcess status:
Status Meaning R Running. This means that the process is running or ready to run. S Sleeping. D Uninterruptible Sleep. Process is waiting for I/O such as a disk drive. T Stopped. Z A defunct or “zombie” process. This is a child process that has terminated, but has not been cleaned up by its parent. < A high priority process (richness) N A low priority process (nice) top:
- %us: user process
- %sy: kernel process
- %ni: nice process
- %id: idle
- %wa: waiting for I/O.
&: put in background;%specify job number (jobspec)kill: -signal_number PIDprocess signal:
| Number | Signal | Meaning |
|---|---|---|
| 1 | HUP | Hangup |
| 2 | INT | Interrupt |
| 9 | KILL | Kill immediately (cannot be ignored) |
| 15 | TERM | Terminate (do clean-up before terminate) |
| 18 | CONT | Continue, restore a process after a STOP |
| 19 | STOP | Stop. This signal causes a process to pause (cannot be ignored) |
| 20 | TSTP | Terminal stop, can be ignored |
-
pstree: Outputs a process list arranged in a tree-like pattern showing the parent/child relationships between processes.
vmstat: Outputs a snapshot of system resource usage;
xload A graphical program that draws a graph showing system load over time.
tload: Similar to the xload program, but draws the graph in the terminal
The environment and packages (apt-get)
Login shell (
/etc/profile, global, or~/.bash_profile,~/.bash_login,~/.profilefor local user) and non-login shell (/etc/bash.bashrc, global, or~/.bashrc)Environment variables:
| Variable | Meaning |
|---|---|
| PATH | A colon-separated list of directories that are searched when you |
| PS1 | Prompt String 1. This defines the contents of your shell prompt |
| TERM | Terminal type |
Apt-get
- Update repo:
apt-get update - Search:
apt-cache search search_string - Update:
apt-get install package_name - Install/update (dpkg):
dpkg --install package_file - Remove:
apt-get remove package_name - List:
dpkg --list - Status:
dpkg --status package_name - Description:
apt-cache show package_name File identification:
dpkg --search file_name
The Debian GNU/Linux FAQ chapter on package management provides an over-
view of package management on Debian systems :
http://www.debian.org/doc/FAQ/ch-pkgtools.en.html
The home page for the RPM project:
http://www.rpm.org
The home page for the YUM project at Duke University:
http://linux.duke.edu/projects/yum/
For a little background, the Wikipedia has an article on metadata:
http://en.wikipedia.org/wiki/Metadata
Storage and networking
Storage related commands:
- mount – Mount a file system
- umount – Unmount a file system
- fsck – Check and repair a file system
- fdisk – Partition table manipulator
- mkfs – Create a file system
- fdformat – Format a floppy disk
- dd – Write block oriented data directly to a device
- genisoimage (mkisofs) – Create an ISO 9660 image file
- wodim (cdrecord) – Write data to optical storage media
md5sum – Calculate an MD5 checksum
Devices:
/dev/hd*: IDE (PATA)/dev/sd*: SCSI (including PATA/SATA hard disks, flash drives, and USB mass storage devices/dev/sr*: Optical disk/dev/lp*: Printersudo tail -f /var/log/messages: System log (including history of removable devices)dd if=input_file of=output_file [bs=block_size [count=blocks]]: Use with caution!Networking:
- ping - Send an ICMP ECHO_REQUEST to network hosts
- traceroute - Print the route packets trace to a network host
- netstat - Print network connections, routing tables, interface statistics, mas-
- uerade connections, and multicast memberships
- ftp - Internet file transfer program
- wget - Non-interactive network downloader
ssh - OpenSSH SSH client (remote login program)
SFTP is based on SSH
For a broad (albeit dated) look at network administration, the Linux Documentation Project provides the Linux Network Administrator’s Guide:
http://tldp.org/LDP/nag2/index.html
Wikipedia contains many good networking articles. Here are some of the basics:
http://en.wikipedia.org/wiki/Internet_protocol_address
http://en.wikipedia.org/wiki/Host_name
http://en.wikipedia.org/wiki/Uniform_Resource_Identifier
Searching, archive and backup
Searching
- locate – Find files by name
- find – Search for files in a directory hierarchy
- xargs – Build and execute command lines from standard input
- touch – Change file times
- stat – Display file or file system status
- Find
- Test:
-type (f/d), -name "regex", -size +/-n(k/M/G etc), -iname(case insensitive),-cmin +/- n(modified more/less than n mins) - Operator:
-not(n) -or(o) -and(a),-andis implicit,\to escape(), the shell characters - Action:
-delete -ls -print -quit- User-defined:
-exec command '{}' ';','to escape shell characters,-exec command'{}' +, apply command on all output,use-okin place of-execto do execution interactively
- User-defined:
- Option:
-depth(Direct find to process a directory’s files before the directory itself. This option is automatically applied when the-deleteaction is specified.),-maxdepth/mindepth levels,-iname: locate inode, can be used to delete inode with which files has weird name xargs: accepts input from standard input and converts it into an argument list for a specified command . e.g.,find ~ -iname '*.jpg' -print0 | xargs --null ls -l: Deal with those containing embedded spaces in file names by changing delimiter from space to null.- gzip/gunzip, bzip2/bunzip2
tar:-x(extract),t(content),c(create),r(append) ,f(followed by tar name),v(--verbose),z(gzip). e.g.,tar cf file_compressed.tar fils_to_compress
important: tar path is relative not absolute!
Using tar with find is a good way of creating incremental backups of a directory tree or an entire system. By using find to match files newer than a timestamp file, we could create an archive that only contains files newer than the last archive, assuming that the timestamp file is updated right after each archive is created.ssh remote-sys 'tar cf - Documents' | tar xf -tar remote file and untar at local, - stands for stdin/stdout
Regex
grep: grep [options] regex [file...]
| Option | Meaning |
|---|---|
| -i | --ignore-case |
| -v | --invert-match (print lines that don't match) |
| -l | --files-with-matches (match only file names) |
| -L | --files-without-match (invert match file names) |
| -n | --line-number (prefix each matching line with the number of the line within the file) |
Metacharacters:
.: match any character in that character position.*accepts any sequence of characters, including an empty string.^and$: cause the match to occur only if the regular expression is found at the beginning of the line (^) or at the end of the line ($). e.g.,^exact_matching$[character_set]:[bg], b or g,[^bg]no b or g,[a-z], a to zPOSIX character classes
| Class | Description |
|---|---|
| [:alnum:] | The alphanumeric characters. In ASCII, equivalent to:[A-Za-z0-9]. |
| [:word:] | [:alnum:] + _ |
| [:alpha:] | The alphabetic characters. In ASCII, equivalent to: [A-Za-z] |
| [:blank:] | Space and tab |
| [:digit:] | 0-9 |
| [:lower:]/[:upper:] | Lower/upper case of characters |
| [:punct:] | Punctuation:[-!"#$%&'()*+,./:;<=>?@[\]_`{\ |
| [:space:] | space, tab, carriage, return, newline, vertical tab, and form feed([ \t\r\n\v\f]) |
- Extended regex
egrep=grep -E: grep with extended regex?: match an element zero or one time+: match an element one or more times*: match an element zero or more timese.g.
^([[:alpha:]]+ ?)+$:match lines consisting of groups of one or more alphabetic characters separated by single spaces{m,n}: min/max repetition m/n. m or n can be omitted
Text processing
- cat – Concatenate files and print on the standard output (-A display invisible symbols)
- sort – Sort lines of text files
- uniq – Report or omit repeated lines
- cut – Remove sections from each line of files
- expand - replace tabs with spaces
- paste – Merge lines of files
- join – Join lines of two files on a common field
- comm – Compare two sorted files line by line
- diff – Compare files line by line (-c context; -u unified; prepare for patch:
diff -Naur) - patch – Apply a diff file to an original
tr – Translate(replace) or delete characters
tr -d '\r' < dos_file > unix_file >convert win to unix (EOL)
- sed – Stream editor for filtering and transforming text
sed -option 'address/regex/replacement/flag': substitute regex with replacementOne of the flag,
gperforms substitution on every instance
| Address | Meaning |
|---|---|
| n | line n |
| $ | the last line |
| /regexp/ | basic regex only |
| addr1,addr2 | lines between addr1 and addr2 |
| addr1~steps | the addr1 line and every "steps" lines after |
| addr1,+n | addr1 and n lines after |
| addr1! | except addr1 |
sedback references: If the sequence \n appears in replacement where n is a number from 1 to 9, the sequence will refer to the corresponding subexpression in the preceding regular expression.
| Sed manipulation | Meaning |
|---|---|
| s | substitute |
| p | |
| d | delete |
| a | append |
| i | insert in front of |
| y/set1/set2 | Perform transliteration by converting characters from set1 to the corresponding characters in set2. sed requires that both sets be equal size |
advanced: awk, perl
aspell – Interactive spell checker
Formatting output and printing
- nl – Number lines
- fold – Wrap each line to a specified length:
fold -w(width) n - fmt – A simple text formatter
- pr – Prepare text for printing
- printf – Format and print data
- groff – A document formatting system
- pr – Convert text files for printing
- lpr – Print files
- a2ps – Format files for printing on a PostScript printer
- lpstat – Show printer status information
- lpq – Show printer queue status
- lprm – Cancel print jobs
- Page description language(PDL), Raster image processor (RIP)
Shell script
#!: shebang, tells the system the name of the interpreterUse
\to escape special operatorsvar="value", use by$var
declare -r CONSTANT_VARlocal:
LOCAL_VARHere command (feed text to command through stdin, single and double quotes within "here documents" lose their special meaning to the shell):
command << token
text
tokenShell function
function_name (parameter) {
commands
return
}Control flow
if commands; then
commands
[elif commands; then
commands...][else
commands]
fi
What included in[]is called test statement. It returns either true or false.
Regex can be evaluated in[[]](bash specification)
Integer operation can be done in(())Exit status:
$?, 0 for success. Check command man page for error code.File operation: -nt(newer than) -ot(older than) -e(exist) -d(directory) -r(regular)
String operation : ==(equal), <,>(sorted after/before), -n(nonezero), -z(zero)
Integer operation: -eq, -ne, -le...
Logical: -a(and,&&), -o(or,||), !(not), =~(inequal)
Loop
While (statement); do
statement
donefor variable [in words]; do
commands
donefor (( expression1; expression2; expression3 )); do
commands
doneBranching:
case word in
pattern commands ;;
...
esacPositional parameters:
\$0(usually filename)\$#(num of args)Parameter expansion:
${to_expand}or\$to_expandGroup command, subshell, wait, trap, named pipe(mkfifo)
[笔记]The Linux command line的更多相关文章
- 《The Linux Command Line》 读书笔记02 关于命令的命令
<The Linux Command Line> 读书笔记02 关于命令的命令 命令的四种类型 type type—Indicate how a command name is inter ...
- 《The Linux Command Line》 读书笔记01 基本命令介绍
<The Linux Command Line> 读书笔记01 基本命令介绍 1. What is the Shell? The Shell is a program that takes ...
- 《The Linux Command Line》 读书笔记04 Linux用户以及权限相关命令
Linux用户以及权限相关命令 查看身份 id:Display user identity. 这个命令的输出会显示uid,gid和用户所属的组. uid即user ID,这是账户创建时被赋予的. gi ...
- Linux Command Line Basics
Most of this note comes from the Beginning the Linux Command Line, Second Edition by Sander van Vugt ...
- Linux Command Line 解析
Linux Command Line 解析 0 处理模型 Linux kernel的启动包括很多组件的初始化和相关配置,这些配置参数一般是通过command line进行配置的.在进行后续分析之前,先 ...
- 15 Examples To Master Linux Command Line History
When you are using Linux command line frequently, using the history effectively can be a major produ ...
- 10 Interesting Linux Command Line Tricks and Tips Worth Knowing
I passionately enjoy working with commands as they offer more control over a Linux system than GUIs( ...
- Reso | The Linux Command Line 的中文版
http://book.haoduoshipin.com/tlcl/book/zh/ 本书是 The Linux Command Line 的中文版, 为大家提供了多种不同的阅读方式. 中英文双语版- ...
- Linux Command Line(II): Intermediate
Prerequisite: Linux Command Line(I): Beginner ================================ File I/O $ cat > a ...
随机推荐
- CKEditor 自主控制图片上传
在ASP.NET中使用CKEditor编辑器,如果想控制图片上传,即把上传的图片路径名存到数据中,可以自定义一个上传功能 首先自定义CKEditor的配置文件 在config.js中添加以下代码,红色 ...
- Android中ListView下拉刷新的实现
ListView中的下拉刷新是非常常见的,也是经常使用的,看到有很多同学想要,那我就整理一下,供大家参考.那我就不解释,直接上代码了. 这里需要自己重写一下ListView,重写代码如下: packa ...
- vs2012中程序集生成无法自动在网站Bin目录下生成Dll文件?(已解决!)
最近,突然发现生成程序集后,网站bin目录下dll没有更新,也没有自动生成dll文件,通过近半个小时的摸索和实验,找到了解决方法: 1.右键网站,不是项目,选择[属性页],在左侧[引用]中如果没有,就 ...
- phper談談最近重構代碼的感受(3)
这篇文章本来该和同一系列的文章一起写的,因为最近换工作的缘故滞后了.重构是非常细碎的叠加,有很多值得注意的地方. 1.消灭过多的临时变量. 有时候过多的无意义的临时变量,真心让人抓狂,特别是过了比较长 ...
- python数据类型以及模块的含义
print(sys.path) #打印环境变量 print(sys.argv) #打印相对路径 print(sys.argv[1]) #打印对应的参数 1.在python最上有时候会导入os模块,表示 ...
- UITabelview的删除
删除的效果 Automatic Bottom Fade left middle none right top 简单删除 先删除数据源里的数据,然后再删除cell,否者会报错 let indexPath ...
- 金蝶KIS专业版替换SXS.dll 遭后门清空数据被修改为【恢复数据联系QQ 735330197,2251434429】解决方法 修复工具。
金蝶KIS专业版 替换SXS.dll 遭后门清空数据(凭证被改为:恢复数据联系QQ 735330197,2251434429)恢复解决方法. [客户名称]:山东青岛福隆发纺织品有限公司 [软件名称]: ...
- cocos2d环境及创建一个自己的项目
一. mac环境: 1.在终端操作,准备好mac系统下的sdk,adt,ndk,ant文件,放在自己的目录中 2.进入mac终端,输入: vim ~/.bash_profile 然后回 ...
- JavaEE XML XSL转换(XSLT)
XSL转换(XSLT) @author ixenos 定义: XSL转换机制可以指定将XML文档转换为其他格式的规则,例如,txt纯文本.XHTML或其他任何XML格式. 用途: XSLT通常用来将某 ...
- centos6.5 安装python3.5
1.CentOS6.5 安装Python 的依赖包 yum groupinstall "Development tools" yum install zlib-devel bzip ...