Liunx命令行基础

粗略整理了 Linux 的基础命令行。

出于种种目的(在自己的服务器上部署博客,在服务器上运行计算量大的机器学习代码,学习 Linux……),我在阿里云上利用学生优惠购买了半年的云服务器 ECS ,为什么不买一年的呢,因为阿里云提示我明年6月份就毕业了,不能买一年的,于是我只好买了半年的。

服务器装了 CentOS 7 的系统,是个 Linux。但是我对于这个“仰慕已久”的系统一窍不通,于是学起来!这篇是我学习Liunx命令行的笔记。

怎样与服务器远程连接呢?首先在网页的阿里云控制台上可以进行远程连接,但查网页上推荐的是用 Xshell 这款软件。如何用 Xshell 连接阿里云服务器在这里就不表了,值得注意的是要记得打开服务器的端口。我第一次连接就是没有打开端口导致连接不成功。

下面就正式开始吧。

一些 Linux 命令

断开与服务器的连接

首先,连接成功后如何断开连接呢?

exit

有两种方式,一种是用 exit 命令:

1
exit

另一种就是 Ctrl + D,也可以断开连接。

从网络下载文件

有 curl 和 wget。

curl

如何从网络上下载文件呢,需要用到 curl 命令,如:

1
curl http://udacity.github.io/ud595-shell/stuff.zip -o things.zip
1
2
3
4
[root@Linux-Gaoke ~]# curl http://udacity.github.io/ud595-shell/stuff.zip -o things.zip
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 144k 100 144k 0 0 65056 0 0:00:02 0:00:02 --:--:-- 65071

wget

用 wget 命令也可以下载文件:

1
wget https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda2-latest-Linux-x86_64.sh

上面是下载了 Minniconda,但在运行安装命令:

1
bash Miniconda2-latest-Linux-x86_64.sh 

后,发生了错误:

1
2
3
4
tar (child): bzip2: Cannot exec: No such file or directory 
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now

原因是没有安装 bzip2 所致。运行命令安装 bzip2:

1
yum install bzip2

就可以顺利安装 Miniconda 啦。

文件操作

ls

列出文件用 ls 命令:

1
2
3
4
5
6
7
[root@Linux-Gaoke ~]# ls
miniconda2 Miniconda2-latest-Linux-x86_64.sh Miniconda-latest-Linux-x86_64.sh
[root@Linux-Gaoke ~]# curl http://udacity.github.io/ud595-shell/stuff.zip -o things.zip
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 144k 100 144k 0 0 65056 0 0:00:02 0:00:02 --:--:-- 65071

列出所有文件(包括隐藏):

1
ls -a

或:

1
ls --all

More Commands

date:

1
2
[root@Linux-Gaoke ~]# date
Sat Aug 19 12:12:32 CST 2017

hostname:

1
2
[root@Linux-Gaoke ~]# hostname
Linux-Gaoke

expr:

1
2
3
[root@Linux-Gaoke ~]# expr 2 + 2
4

expr命令为Linux中的命令,一般用于整数值计算,但也可用于字符串操作。

host:

命令返回一个主机的网际地址(当Hostname 参数被指定时),或返回主机名(当Address参数被指定时)。

host这个程序是 bind-utils包里面的 ,所以要先安装 bind-utils :

1
yum install bind-utils

然后就可以了。

1
2
3
4
5
6
7
[root@Linux-Gaoke ~]# host udacity.com
udacity.com has address 45.79.141.183
udacity.com mail is handled by 20 alt2.aspmx.l.google.com.
udacity.com mail is handled by 20 alt1.aspmx.l.google.com.
udacity.com mail is handled by 30 aspmx3.googlemail.com.
udacity.com mail is handled by 30 aspmx2.googlemail.com.
udacity.com mail is handled by 10 aspmx.l.google.com.

再看看我的博客地址:

1
2
3
4
5
[root@Linux-Gaoke ~]# host gaoke.online
gaoke.online is an alias for geokeke.github.io.
geokeke.github.io is an alias for sni.github.map.fastly.net.
sni.github.map.fastly.net has address 151.101.73.147
sni.github.map.fastly.net has IPv6 address 2a04:4e42:11::403

echo:

1
2
[root@Linux-Gaoke ~]# echo you rock
you rock

bash:

1
2
3
4
5
6
7
8
[root@Linux-Gaoke ~]# bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

uname:

1
2
[root@Linux-Gaoke ~]# uname
Linux

uname 是Linux命令,用于显示当前操作系统名称。

history:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@Linux-Gaoke ~]# history 
1 python -v
2 man man
3 i love you xuyuan
4 exit
5 ls
6 curl http://udacity.github.io/ud595-shell/stuff.zip -o things.zip
7 ls
8 date
9 hostname
10 expr 2+2
11 expr 2 + 2
12 host udacity.com
13 echo you rock
14 bash --version
15 uname
16 history

查看命令历史。也可以用 Ctrl + R,然后搜索历史。还可以用上下箭头查看输入过的命令。

rm 删除:

1
rm word.txt

Shell 命令与 Python 函数的异同

相同点:

  • 都是代码单元
  • 都有名称
  • 都能接受变量

不同点:

  • 环境不同
  • 目的不同

uptime:

显示系统已经运行了多长时间,它依次显示下列信息:当前时间、系统已经运行了多长时间、目前有多少登陆用户、系统在过去的1分钟、5分钟和15分钟内的平均负载。

1
2
[root@Linux-Gaoke ~]# uptime
13:34:55 up 16:57, 3 users, load average: 0.00, 0.01, 0.05

Linux 中的文件操作

解压、合并等

解压文件 unzip:

Linux 系统没有自带的压缩解压工具;需要我们自己安装;当用到zip或者unzip如果没有安装就会出现unzip: Command Not Found 或 zip: Command Not Found;出现这个事因为没有安装unzip和zip。

1
yum install -y unzip zip

然后就可以用了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
[root@Linux-Gaoke ~]# unzip things.zip 
Archive: things.zip
inflating: bivalves.txt
inflating: cephalopods.txt
inflating: gastropods.txt
inflating: mustelidae.txt
extracting: .secret
creating: ocean/
creating: ocean/stuff/
creating: ocean/stuff/misc/
extracting: ocean/stuff/otters
extracting: ocean/water
creating: junk/
creating: junk/parts/
creating: junk/parts/a/
extracting: junk/parts/a/apple-cores
creating: junk/parts/b/
extracting: junk/parts/b/banana-peels
creating: junk/parts/c/
extracting: junk/parts/c/clam-shells
creating: globbing/
extracting: globbing/app.css
extracting: globbing/app.html
extracting: globbing/app.js
extracting: globbing/bean.png
extracting: globbing/bear.png
extracting: globbing/beer.png
extracting: globbing/bees.png
extracting: globbing/DAVE.JPG
extracting: globbing/favicon.png
extracting: globbing/index.html
extracting: globbing/JADE.jpg
extracting: globbing/john.jpg
extracting: globbing/rose.JPG
inflating: gastropods_draft.txt
inflating: TheWindintheWillows.txt

cat :

cat 是 concatenate (合并)的缩写,cat主要有三大功能:

  • 一次显示整个文件:

    1
    cat filename
  • 从键盘创建一个文件:

    1
    cat > filename  
  • 将几个文件合并为一个文件:

    1
    cat file1 file2 > file

在服务器中运行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@Linux-Gaoke ~]# cat bivalves.txt gastropods_draft.txt 
California Mussel: A large edible mussel, a marine bivalve mollusk in the family Mytilidae. This species is native to the west coast of North America, occurring from northern Mexico to the Aleutian Islands of Alaska.
Common Cockle: Cerastoderma edule, commonly known as the common cockle, is a species of edible saltwater clam, a marine bivalve mollusc in the family Cardiidae, the cockles.
This species is found in coastal areas of the eastern Atlantic Ocean.
Giant Clam: The giant clam (Tridacna gigas), known as pā’ua in Cook Islands Māori, is a clam that is the largest living bivalve mollusk. T. gigas is one of the most endangered clam species. Antonio Pigafetta documented these in his journal as early as 1521.
Geoduck: A species of very large, edible, saltwater clam in the family Hiatellidae. The geoduck is native to the west coast of North America. The geoduck is both one of the largest clams in the world, and one of the longest-lived animals of any type.
Pearl Oyster: Pinctada is a genus of saltwater clams, marine bivalve molluscs in the family Pteriidae, the pearl oysters. These oysters have a strong inner shell layer composed of nacre, also known as "mother of pearl". Pearl oysters are not closely related to either the edible oysters of family.
Pacific Razor Clam: The Pacific razor clam, Siliqua patula, is a species of large edible marine bivalve mollusc in the family Pharidae. Pacific razor clams are highly desirable and edible, collected both commercially and by recreational harvesters. Razor clams, like other shellfish, may sometimes accumulate dangerous levels of domoic acid, a marine toxin.
Quahog: The hard clam (Mercenaria mercenaria), also known as a quahog (or quahaug), round clam, or hard-shell (or hard-shelled) clam, is an edible marine bivalve mollusk that is native to the eastern shores of North America and Central America.
Yessoi Scallop: Patinopecten yessoensis (Yesso scallop, Giant Ezo scallop, Ezo giant scallop) is a species of scallop. Its name Yesso/Ezo refers to its being found north of Japan. Its tissues bioaccumulate algal yessotoxins, which are studied extensively.
Zebra Mussel: The zebra mussel (Dreissena polymorpha) is a small freshwater mussel. This species was originally native to the lakes of southern Russia. However, the zebra mussel has been accidentally introduced to numerous other areas, and has become an invasive species in many different countries worldwide.

Source: Wikipedia, The Free Encyclopedia
Banana Slug: Banana slug is a common name for three North American species of terrestrial slug in the genus Ariolimax. These slugs are often yellow in color and are sometimes spotted with brown, like a ripe (or overripe) banana.
Ghost Slug: The ghost slug, Selenochlamys ysbryda, is a species of predatory air-breathing land slug. Unlike the majority of slugs, it is a carnivore, feeding on earthworms using its blade-like teeth.
Limpet: A limpet is an aquatic snail with a shell that is broadly conical in shape. "Limpet" informally refers to any gastropod whose shell has no obvious coiling, like the coiling which can be seen in the shells of garden snails or winkles.
Nudibranch: A nudibranch is a member of the Nudibranchia, a group of soft-bodied, marine gastropod mollusks which shed their shells after their larval stage. They are noted for their often extraordinary colours and striking forms.
Sea Snail: Sea snail is a common name for snails that normally live in saltwater, in other words marine gastropods. The taxonomic class Gastropoda also includes snails that live in other habitats, such as land snails and freshwater snails. Many species of sea snails are edible and exploited as food sources by humans.

Source: Wikipedia, The Free Encyclopedia

打印出了全部的文本内容。但是我还没看这里说了些啥,后面看看哈哈。

Tip:输入命令时,可用按 Tab 补齐。

wc:

Linux系统中的wc(Word Count)命令的功能为统计指定文件中的字节数、字数、行数,并将统计结果显示输出。

1

[root@Linux-Gaoke ~]# wc bivalves.txt 12 393 2483 bivalves.txt

1
2
3
4
5
6
7
8
9
10

### diff:

比较文件,显示文件不同之处。

​```shell
[root@Linux-Gaoke ~]# diff gastropods.txt gastropods_draft.txt
5d4
< Sea Angel: Sea angels (clade Gymnosomata) are a large group of small, swimming sea slugs classified into six different families. In this clade, the foot of the gastropod has developed into wing-like flapping appendages (parapodia) and their shells have been lost. Both adaptations suit their free-swimming oceanic lives.

cowsay:

这是个有趣的命令。首先要安装:

1
yum install -y cowsay

安装完了就可以用了:

1
2
3
4
5
6
7
8
9
10
[root@Linux-Gaoke ~]# cowsay Hello,Yuan!
_____________
< Hello,Yuan! >
-------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||

是不是很可爱!还可以自定义字符,下面是用 v 代替牛舌头:

1
2
3
4
5
6
7
8
9
[root@Linux-Gaoke ~]# cowsay -T v I love you!
_____________
< I love you! >
-------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
v ||----w |
|| ||

还可以画企鹅:

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@Linux-Gaoke ~]# cowsay -f tux I love you,too!
_________________
< I love you,too! >
-----------------
\
\
.--.
|o_o |
|:_/ |
// \ \
(| | )
/'\_ _/`\
\___)=(___/

man 命令:

man 是手册页,不会就可以 man 一下。比如不知道 cowsay 更具体的用法:

1
man cowsay

会出现:

1
2
3
4
5
6
7
8
cowsay(1)                         General Commands Manual                         cowsay(1)

NAME
cowsay/cowthink - configurable speaking/thinking cow (and a bit more)

SYNOPSIS
cowsay [-e eye_string] [-f cowfile] [-h] [-l] [-n] [-T tongue_string] [-W column]
[-bdgpstwy]

对于命令的详细介绍。

要谨慎的命令:rm -rf

不要运行!会删除 Linux 的所有文件内容。

-r is for recursive, and -f is for force.

Just to be clear: This command is not good for your system. Don't run it. Keep watching ...

Line Based Programs

一次性与交互命令

sort

1
2
3
4
5
6
7
8
9
10
[root@Linux-Gaoke ~]# ping baidu.com
PING baidu.com (220.181.57.217) 56(84) bytes of data.
64 bytes from 220.181.57.217 (220.181.57.217): icmp_seq=1 ttl=51 time=27.8 ms
64 bytes from 220.181.57.217 (220.181.57.217): icmp_seq=2 ttl=51 time=28.0 ms
64 bytes from 220.181.57.217 (220.181.57.217): icmp_seq=3 ttl=51 time=28.0 ms
^C
--- baidu.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 27.862/27.967/28.032/0.155 ms

按 Ctrl + D 执行并退出。

ping

1
2
3
4
5
6
7
8
9
[root@Linux-Gaoke ~]# ping baidu.com
PING baidu.com (220.181.57.217) 56(84) bytes of data.
64 bytes from 220.181.57.217 (220.181.57.217): icmp_seq=1 ttl=51 time=27.8 ms
64 bytes from 220.181.57.217 (220.181.57.217): icmp_seq=2 ttl=51 time=28.0 ms
64 bytes from 220.181.57.217 (220.181.57.217): icmp_seq=3 ttl=51 time=28.0 ms
^C
--- baidu.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 27.862/27.967/28.032/0.155 ms

按 Ctrl + C 退出。

bc:

计算器

less:

相比于全部显示,显示更少的内容:

1
less bivalves.txt 

nano 编辑器

这个的具体用法用到再补充吧。

Linux 文件系统

文件系统树

  • 文件 文件名如果有空格,要加引号
  • 文件夹

Linux 用正斜杠“/”区分路径。Win 用反的。

/ 是根目录,~是主目录。

pwd

用 pwd 命令可以打印出工作目录:

1
2
3
[root@Linux-Gaoke ~]# pwd
/root

cd

切换目录用 cd:

1
cd ..

这样会返回上一级。

cd 不加参数会返回主目录(不是跟目录)。

mv 移动和 cp 复制

1
mv beach.jpg Photos

mkdir 创建新目录

1
mkdir Photos

rmdir 删除空目录

1
rmdir Photos

当目录不是空的,要用

1
rm -r junk(目录名)

将目录的内容清空。

glob 通配

用 * 表示,可以通配从 0 到 n 个字符:

1
2
3
[root@Linux-Gaoke ~]# ls *txt
bivalves.txt gastropods_draft.txt mustelidae.txt
cephalopods.txt gastropods.txt TheWindintheWillows.txt

每个包含 txt 的都会列出来。

还有 ? 号,一个问号代表一个字符。

就先这样吧,后面再修改补充咯。