09 linux命令执行顺序控制与管道

2019-06-24  本文已影响0人  小码码

资料来源:https://www.shiyanlou.com/courses/1

1 多条命令顺序执行

sudo apt-get update;sudo apt-get install some-tool;some-tool 中间用;分开

2 有选择的执行

which cowsay>/dev/null && cowsay -f head-in ohch~ 第一句返回的系统状态为0时执行后面一句
echo ? 从?环境变量获取上一次命令的返回结果
which cowsay>/dev/null || echo "cowsay has not been install, please run 'sudo apt-get install cowsay' to install" 第一句返回的系统状态不为0时执行后面一句

3 管道

管道是一种通信机制,通常用于进程间的通信,它表现出来的形式就是将前面每一个进程的输出(stdout)直接作为下一个进程的输入(stdin)。在命令行中用|分开。

ls -al /etc | less   通过管道将前一个命令(ls)的输出作为下一个命令(less)的输入,然后就可以一行一行地看。
export | grep ".*yanlou$"   查看环境变量中以"yanlou"结尾的字符串
$ wc /etc/passwd  统计并输出一个文件中行、单词和字节的数目
$ wc -l /etc/passwd   行数
$ wc -w /etc/passwd   单词数
$ wc -c /etc/passwd  字节数
$ wc -m /etc/passwd  字符数
$ wc -L /etc/passwd  最长行字节数
ls -dl /etc/*/ | wc -l   统计 /etc 下面所有目录数
$ cat /etc/passswd | sort   默认为字典排序
$ cat /etc/passwd | sort -r  反转排序
$ cat /etc/passwd | sort -t':' -k 3   特定字段排序
$ cat /etc/passwd | sort -t':' -k 3 -n  按数字排序
# 删除 "hello shiyanlou" 中所有的'o','l','h'
$ echo 'hello shiyanlou' | tr -d 'olh'
# 将"hello" 中的ll,去重为一个l
$ echo 'hello' | tr -s 'l'
# 将输入文本,全部转换为大写或小写输出
$ echo 'input some text here' | tr '[:lower:]' '[:upper:]'
# 上面的'[:lower:]' '[:upper:]'你也可以简单的写作'[a-z]' '[A-Z]',当然反过来将大写变小写也是可以的
# 查看 /etc/protocols 中的不可见字符,可以看到很多 ^I ,这其实就是 Tab 转义成可见字符的符号
$ cat -A /etc/protocols
# 使用 col -x 将 /etc/protocols 中的 Tab 转换为空格,然后再使用 cat 查看,你发现 ^I 不见了
$ cat /etc/protocols | col -x | cat -A
# 创建两个文件
$ echo '1 hello' > file1
$ echo '1 shiyanlou' > file2
$ join file1 file2
# 将/etc/passwd与/etc/shadow两个文件合并,指定以':'作为分隔符
$ sudo join -t':' /etc/passwd /etc/shadow
# 将/etc/passwd与/etc/group两个文件合并,指定以':'作为分隔符, 分别比对第4和第3个字段
$ sudo join -t':' -1 4 /etc/passwd -2 3 /etc/group
$ echo hello > file1
$ echo shiyanlou > file2
$ echo www.shiyanlou.com > file3
$ paste -d ':' file1 file2 file3
$ paste -s file1 file2 file3
上一篇 下一篇

猜你喜欢

热点阅读