命令行与shell编程系列文章目录
第一章 什么是命令行
第二章 文件权限
第三章 文件的处理
第四章 磁盘和文件系统
第五章 理解shell解析器和shell进程
前言
计算机最主要的工作就是处理数据,也就是如何经过一系列的计算机程序得到人类主观意识需要的数据。从存储方面来说,如何快速查看所需数据(文件)也是数据处理能力的指标。
输入和输出
Linux系统中有一句名言:一切皆文件。Linux用文件描述符来标识每个文件对象,文件描述符是一个非负整数。其中系统保留前三个文件描述符,(0, 1, 2)
文件描述符 | 缩写 | 描述 | 符号 |
---|---|---|---|
0 | STDIN | 标准输入 | < |
1 | STDOUT | 标准输出 | 1> |
2 | STDERR | 标准错误 | 2> |
输入字符回车后终端自动打印相同字符,cat默认从标准输入(键盘)获取信息后输出到标准输出
# cat
testcat
testcat
d
d
STDIN重定向到文件的输入
# cat < testFile
112233
STDOUT重定向到文件
# cat 1> catinfo
sds
sddsas
# cat catinfo
sds
sddsas
# cat inexistenceFile STDERR重定向到文件,其中错误输入到终端,需要2>重定向到文件
cat: can't open 'inexistenceFile': No such file or directory
# cat inexistenceFile 2> errorinfo
# cat errorinfo
cat: can't open 'inexistenceFile': No such file or directory
管道
若需要把一个命令的输出作为一个命令的输入,除了使用重定向外,使用管道是一个快捷的方法
# sort file
a
b
b
c
d
e
e
f
g
h
j
k
m
s
v
# ps | sort | more
1 root {linuxrc} init
2 root [kthreadd]
3 root [ksoftirqd/0]
6 root [khelper]
7 root [kdevtmpfs]
8 root [sync_supers]
9 root [bdi-default]
10 root [kblockd]
11 root [sytem]
12 root [khubd]
13 root [kworker/0:1]
14 root [cfg80211]
15 root [rpciod]
16 root [kswapd0]
17 root [fsnotify_mark]
18 root [nfsiod]
19 root [crypto]
25 root [SunxiDisCommit]
26 root [Sunxi_WB]
27 root [kapmd]
28 root [spi.0]
29 root [kworker/u:1]
34 root [kworker/0:2]
--More--
文件信息过滤和查找
# cat /etc/passwd
root:x:0:0:root:/root:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/false
bin:x:2:2:bin:/bin:/bin/false
sys:x:3:3:sys:/dev:/bin/false
sync:x:4:100:sync:/bin:/bin/sync
mail:x:8:8:mail:/var/spool/mail:/bin/false
www-data:x:33:33:www-data:/var/www:/bin/false
operator:x:37:37:Operator:/var:/bin/false
nobody:x:99:99:nobody:/home:/bin/false
s3:x:1000:1000:Linux User,,,:/home/s3:/bin/sh
# cut -f1 -d: /etc/passwd
root
daemon
bin
sys
sync
mail
www-data
operator
nobody
s3
#
# find / -name "*.ko"
/lib/modules/3.4.39/8188eu.ko
/opt/kernel/ker/8188eu.ko
# find / -type f -size +6000k
/swap/swapfile
/root/mask_backup_data
查找到文件并且执行删除动作
find . -name file -exec rm {} \;
查找etc文件夹下包含root字段的文件
# grep root -rl /etc/
/etc/os-release
/etc/hosts
/etc/udhcpd.conf
/etc/mtab
/etc/network/interfaces
/etc/libnl/classid
/etc/group-
/etc/passwd-
/etc/shadow-
/etc/hostname
/etc/fstab
/etc/group
/etc/passwd
/etc/shadow
# sed 's/root/ROOT/g' /etc/passwd
ROOT:x:0:0:ROOT:/ROOT:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/false
bin:x:2:2:bin:/bin:/bin/false
sys:x:3:3:sys:/dev:/bin/false
sync:x:4:100:sync:/bin:/bin/sync
mail:x:8:8:mail:/var/spool/mail:/bin/false
www-data:x:33:33:www-data:/var/www:/bin/false
operator:x:37:37:Operator:/var:/bin/false
nobody:x:99:99:nobody:/home:/bin/false
# awk -F ":" '{print $1,$3 }' /etc/passwd
root 0
daemon 1
bin 2
sys 3
sync 4
mail 8
www-data 33
operator 37
nobody 99
s3 1000