Bash Shell快速上手

我本来打算看8个小时shell的视频教学,但是只看了3个小时,后面没看,觉得太慢了,我就直接拿起一本书《跟老男孩学Linux运维》,因为我主要是工作当时需要写脚本,我就快速拿起了本书来。后面就去了一个练习平台做了一些baisc的shell题目。下面是我自己的总结

在线实验环境:点击https://shell.aliyun.com进入 需要使用支付宝登陆


shell环境


STDIN,STDOUT,STDERR,I/O Redirection.

例子:

ls > outfile 将ls的内容重定向到outfile

ls >> outfile 将ls输出的内容追加到outfile

grep root /etc/* 2>/dev/null 这里2代表的是错误, /dev/null 代表空设备文件,它等价于一个仅仅写文件,全部写入它的内容都会永远丢失.

grep root /etc/* 2>/dev/null > grepout.txt 标准错误输出到 /dev/null, 标准输出写到grepout.txt

Internal command

尽量使用,会更快,使用man可以查看对应的帮助

例子:

man bash

Using Variables

查看环境变量命令: env

定义变量: key=vaule =号没有空格, 输出echo $key或者echo ${key}]

导出: export key=value 在当前终端有效

别名 alias key='xxxx' 例子 alias la='ls -A', 在终端输入la就等于ls -A

Bash Startup Files

/etc/profile 每个用户登录,/etc/bashrc 打开子shell,用户特定的~/.bash_prfile ~/.bashrccat

Understanding Exit Codes

在linux当中0是正常退出,其它数字都是错误退出。不过这个是由用户定义的.


要知道的命令

echo -e转义输出 tab 换行

shell@Alicloud:~$ echo -e "a	b	c
d	e	d"
a       b       c
d       e       d

printf %s 字符串 %d整型 %f 浮点型

shell@Alicloud:~$ printf "%s
" "hello" "my  world"
hello
my  world

echo使用比较多,prinf格式化都是统一。

set, shopt 改变shell的配置

shell@Alicloud:~$ ls
shell@Alicloud:~$ set -x
shell@Alicloud:~$ ls
+ ls --color=auto

模式匹配

*匹配0或者更多

?匹配任何字符

[...]匹配任何在列表里的字符

@ 匹配出现过一次的

shell@Alicloud:~/files$ touch .txt e.txt ee.txt eee.txt
shell@Alicloud:~/files$ ls *.txt
eee.txt  ee.txt  e.txt
shell@Alicloud:~/files$ ls ?(e).txt
e.txt  .txt
shell@Alicloud:~/files$ ls *(e).txt
eee.txt  ee.txt  e.txt  .txt
shell@Alicloud:~/files$ ls +(e).txt
eee.txt  ee.txt  e.txt
shell@Alicloud:~/files$ ls @(e).txt
e.txt

grep用法:grep 字符串 文件。 -v 排除哪些字符串 -E 正则表达式

理解IFS(internal field separator)内部字符分隔开

cut -d 分隔字符 -f 第几列 文件

shell@Alicloud:~$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
shell@Alicloud:~$ cut -d : -f 3 /etc/passwd
0
1
2

sort排序,默认使用ASCII, sort -n按数字

tail, head

tail -3 /etc/passwd 最后3行

sed

sed 's/Tom/Anna/g' employee.txt 将Tom的全部替换成Anna

awk -F IFS(分隔字符) '{}' 要执行的命令 文件

shell@Alicloud:~$ awk -F : '{print $4}' /etc/passwd
0
1
2
3


if else 语法 :训练https://www.hackerrank.com/challenges/bash-tutorials---comparing-numbers/problem?isFullScreen=true

read X
read Y
if [ $X -lt $Y ]; then
    echo "X is less than Y"
elif [ $X -gt $Y ]; then
    echo "X is greater than Y"
else
    echo "X is equal to Y"
fi

[[]]数值判断

read X
read Y
read Z
if [[ $X == $Y && $Y == $Z ]]; then
    echo "EQUILATERAL"
elif [[ $X != $Y && $X != $Z && $Y != $Z ]]; then
    echo "SCALENE"
else
    echo "ISOSCELES"
fi
展开阅读全文

页面更新:2024-03-19

标签:在线   终端   上手   字符串   字符   例子   命令   定义   错误   快速   文件   内容

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top