学习 Unix 常用命令

第一个是 man 命令,作用是:"Display system documentation",我是 manual 的缩写。通过这个命令,我们能了解接下来要学习的命令的文档。

ls, pwd, cd 的基本用法我觉得不需要额外说明。

man

命令的主要说明文档。

如果要查询一个命令的一个参数,要怎么做?

比如查找 find -type

这其实属于 grep 命令的范畴了,命令是 man find | grep -e '-type'

cp

cp命令的复杂性源于文件系统的复杂性。常遇到的情况有:如何处理软链接文件?

如果目标文件存在,怎么办?如果目标文件存在,但是打不开,怎么处理?

source file 是一个文件夹的话,要复制多少,是复制整个文件夹,还是部分?

 

这些都能通过 cp 的参数来解决。

对于已存在的目标文件

-f 在权限范围内,强制删除然后新建并复制过去;

-i 提示用户,并等待用户选择

-n 不覆盖已存在文件,并且不会提示

软链接

-L    If the -R option is specified, all symbolic links are followed.

这个解释少了半截。搜索了一下,完整的意思是这样““Follows the links in the source to find the file to copy instead of copying the links ””

 

-P    If the -R option is specified, no symbolic links are followed.  This is the default.

默认情况下,只复制软链接而不复制它所对应的文件

源文件为文件夹

-R    If source_file designates a directory, cp copies the directory and

           the entire subtree connected at that point.  If the source_file

           ends in a /, the contents of the directory are copied rather than

           the directory itself.  This option also causes symbolic links to be

           copied, rather than indirected through, and for cp to create spe-

           cial files rather than copying them as normal files.  Created

           directories have the same mode as the corresponding source direc-

           tory, unmodified by the process' umask.

 

           In -R mode, cp will continue copying even if errors are detected.

 

           Note that cp copies hard-linked files as separate files.  If you

           need to preserve hard links, consider using tar(1), cpio(1), or

           pax(1) instead.

这里有一个比较隐蔽的选项,如果源文件是文件夹,并且它的路径以 '/' 结尾,就复制该文件夹下的所有文件过去(不放在该文件夹中)而不是复制该文件夹过去。

我们做一下测试

mkdir source_dir target_dir
$ touch source_dir/file1 source_dir/file2
$ ls source_dir
file1	file2
$ ls target_dir
$ cp -R source_dir target_dir/
$ ls target_dir/
source_dir
$ cp -R source_dir/ target_dir/
$ ls target_dir/
file1		file2		source_dir

这些参数可以组合使用,组合使用后也有问题,如果参数的作用冲突了,你还要弄清冲突后的效果。这里我暂时不深入了。

rm

rm 与 cp 类似,也存在文件夹、软链接的问题。

不带参数的 rm 只能删除非目录类型的文件。

删除文件夹

-d          Attempt to remove directories as well as other types of files.

尝试了一下,发现不能移除非空文件夹

如果要移除非空文件夹,使用 -R

软链接

The rm utility removes symbolic links, not the files referenced by the links.

mkdir

创建文件夹。

默认情况下,如果要创建的文件夹的中间路径有不存在的,那么会报错;

如果有 -p 选项,那么会自动创建中间不存在的文件夹;

ln

man ln 的说明看的有点糊涂,于是找到了 ln (Unix) 上的解释

通过链接文件,不同的文件名可以指向同一个文件。

ln 可以创建两种类型的链接文件:

  1. 符号链接,也称软链接,这是指向另一个不同路径文件的一个符号路径。
  2. 硬链接,这是一个存储了链接建立时它所指向文件的实际数据的文件副本。

从以下命令示例可看出两种链接文件的区别:

$ echo '文件内容' > oringinal.file
$ ln oringinal.file hardlink.file
$ ln -s oringinal.file softlink.file
$ cat softlink.file
文件内容
$ rm oringinal.file
$ cat softlink.file
cat: softlink.file: 没有那个文件或目录
$ cat hardlink.file
文件内容

原始文件被删除后,符号链接将失效,访问软链接时,会提示找不到文件,但硬链接文件还在,而且还保存有原始文件的内容。

硬链接与 cp 有什么不一样?  

要理解这个,先要理解 inodes。这里 http://teaching.idallen.com/cst8207/12f/notes/460_links_and_inodes.html 讲的很详细。看完就就会理解下面的结论。

Thus, on Unix, a file can have many names, even across different directories. You may use any of the several names of a file to find the inode for the file. Unix calls these names "pointers" or "links" to the file.

 

Note that the "rm" command does not delete a file - it only deletes a name-inode map for a file. Only when all the name-inode maps are gone does the actual file data space get reclaimed.

 读完上面那篇文章,我们能够知道,如果更改硬链接的文件,那么原始文件、软链接的文件都会变化,因为它们都指向相同的 inodes。但是复制出的文件就不会变化,因为是不同的 inodes 了。代码如下:

$ echo 'file content' > original.file
$ ln original.file hardlink.file
$ ln -s original.file softlink.file
$ cp original.file copied_original.file
$ rm original.file
$ ln hardlink.file original.file
# 更改文件
$ vim original.file
# 更改后的文件内容
$ cat original.file
file content
updated!!!
$ cat hardlink.file
file content
updated!!!
$ cat softlink.file
file content
updated!!!
# 使用 cp 复制出来的没有变化
$ cat copied_original.file
file content

  

mv

移动文件(夹)。可以看成是 cp 与 rm 的结合

rm -f destination_path && \
cp -pRP source_file destination && \
rm -rf source_file    
cp -pRP

从源文件复制过去,保留各种属性信息,复制软链接而不是它的源文件,如果是文件夹,复制整个文件夹过去。

touch

改变文件的访问和修改时间。如果文件不存在,那么创建这个文件,文件权限为默认权限。

cat

cat -- concatenate and print files

     The command:

 

           cat file1 file2 > file3

 

     will sequentially print the contents of file1 and file2 to the file file3, truncating file3 if it already exists.  See the manual page for your shell (i.e., sh(1)) for more

     information on redirection.

 

     The command:

 

           cat file1 - file2 - file3

 

     will print the contents of file1, print data it receives from the standard input until it receives an EOF (`^D') character, print the contents of file2, read and output contents

     of the standard input again, then finally output the contents of file3.  Note that if the standard input referred to a file, the second dash on the command-line would have no

     effect, since the entire contents of the file would have already been read and printed by cat when it encountered the first `-' operand.

cat file1 file2 > file3 会将 file1, file2 的内容联合起来,写入到 file3。file3 的内容会丢失。

cat file1 - file2 - file3 会打印输入的,直到 EOF 为止。不知道这个的作用是什么。

kill/pkill/killall

向对应进程发送信号

 

kill 根据 pid 找到进程,默认情况下发送 -SIGTERM 信号;

pkill 与 killall 根据一定条件找到进程,然后给这些进程发送信号;

pkill 与 killall 

来源:https://unix.stackexchange.com/questions/91527/whats-the-difference-between-pkill-and-killall

The pgrep and pkill utilities were introduced in Sun's Solaris 7 and, as g33klord noted, they take a pattern as argument which is matched against the names of running processes. While pgrep merely prints a list of matching processes, pkill will send the specified signal (or SIGTERM by default) to the processes. The common options and semantics between pgrep and pkill comes in handy when you want to be careful and first review the list matching processes with pgrep, then proceed to kill them with pkillpgrep and pkill are provided by the the procps package, which also provides other /proc file system utilities, such as pstopfreeuptime among others.

The killall command is provided by the psmisc package, and differs from pkill in that, by default, it matches the argument name exactly (up to the first 15 characters) when determining the processes signals will be sent to. The -e--exact option can be specified to also require exact matches for names longer than 15 characters. This makes killall somewhat safer to use compared to pkill. If the specified argument contains slash (/) characters, the argument is interpreted as a file name and processes running that particular file will be selected as signal recipients. killall also supports regular expression matching of process names, via the -r--regexp option.

There are other differences as well. The killall command for instance has options for matching processes by age (-o--older-than and -y--younger-than), while pkill can be told to only kill processes on a specific terminal (via the -t option). Clearly then, the two commands have specific niches.

Note that the killall command on systems descendant from Unix System V (notably Sun's SolarisIBM's AIX and HP's HP-UX) kills all processes killable by a particular user, effectively shutting down the system if run by root.

The Linux psmisc utilities have been ported to BSD (and in extension Mac OS X), hence killallthere follows the "kill processes by name" semantics.

从上文可以看出,pkill 与 pgrep 是一对,你可以预先运行 pgrep 看到 pkill 要找的进程。

killall 默认情况下,匹配进程名的前15个字符,也可以调整选项进行完全匹配。killall 还可以通过创建时间来筛选,但我在 man killall 中没有找到;

可发送的信号

Signal NameSignal NumberDescription
SIGHUP 1 Hang up detected on controlling terminal or death of controlling process
SIGINT 2 Issued if the user sends an interrupt signal (Ctrl + C)
SIGQUIT 3 Issued if the user sends a quit signal (Ctrl + D)
SIGFPE 8 Issued if an illegal mathematical operation is attempted
SIGKILL 9 If a process gets this signal it must quit immediately and will not perform any clean-up operations
SIGALRM 14 Alarm clock signal (used for timers)
SIGTERM 15 Software termination signal (sent by kill by default)

来源:https://www.tutorialspoint.com/unix/unix-signals-traps.htm

SIGKILL 与 SIGTERM 的区别

SIGTERM is the termination signal. The default behavior is to terminate the process, but it also can be caught or ignored. The intention is to kill the process, gracefully or not, but to first allow it a chance to cleanup.

SIGKILL is the kill signal. The only behavior is to kill the process, immediately. As the process cannot catch the signal, it cannot cleanup, and thus this is a signal of last resort.

来源:https://www.quora.com/What-is-the-difference-between-the-SIGINT-and-SIGTERM-signals-in-Linux

top

显示系统进程的排序好的信息。可以从各个角度、参数来查看进程的信息,所以参数很多。

有四种不同的模式

       -c <mode>

              Set event counting mode to <mode>.  The supported modes are:

 

              a      Accumulative mode.  Count events cumulatively, starting at the launch of top.  Calculate  CPU  usage  and  CPU  time

                     since the launch of top.

 

              d      Delta  mode.   Count  events  relative to the previous sample.  Calculate CPU usage since the previous sample.  This

                     mode by default disables the memory object map reporting.  The memory object map reporting may  be  re-enabled  with

                     the -r option or the interactive r command.

 

              e      Absolute mode.  Count events using absolute counters.

 

              n      Non-event mode (default).  Calculate CPU usage since the previous sample.

Accumulative mode

Delta  mode

Absolute mode

Non-event mode

可以以不同的关键字排序,详情见 man top 中的 -o 选项

 

fg/bg

看这篇文章 《Bg, Fg, &, Ctrl-Z – 5 Examples to Manage Unix Background Jobs》

运行过程中会在当前的 terminal 显示输出,比如

find: /System/Library/Caches/com.apple.coresymbolicationd: Permission denied  

杀死一个后台任务后,并不会消失,而是变为 Terminated 状态

$ kill %1
$ jobs
[1]+  Terminated: 15          find / -ctime -1 > /tmp/changed-file-list.txt

 

后台任务与前台任务的区别

在同一个 shell 中,你需要等待前台任务执行完才能执行下一条指令,而后台任务就不用这样;

如果后台任务需要输入,你还是要把它弄回前台,才能继续;

当退出 shell 后,后台任务一样会被杀死。

crontab

来源:Linux crontab command

crontab 的全称是 cron table,是由 cron 去执行 crontable 中的任务。

我使用 MACOS,发现要用 sudo crontab 才能创建成功。对应的 crontab 在 root 用户下。

find

来源:A collection of Unix/Linux ‘find’ command examples

find 命令可以根据搜索条件来搜索整个文件系统以获取对应的文件或文件夹。并且,find 命令还可以与其他命令结合使用,比如 grep, mv, rm 等等。

常用搜索条件

文件类型

通过 man find,然后找到 -type。

文件名

-name

文件其他属性

mtime 修改时间。但是在 man find 中没有写。

修改时间

grep

打印出符合 pattern 的行

 

pattern 中包含 '-

使用 -e 参数

$grep -e -type file1 file2
file1:file1 content with - '-type'

 

还可以使用 -R 递归搜索整个文件夹中的文件

 

posted @ 2017-06-01 18:04  Jay54520  阅读(274)  评论(0编辑  收藏  举报