Bash Scripting Tutorial for Beginners
Bash Shell Scripting Definition
- Bash:Bourne-Again SHell
Bash is a command language interpreter.conclusion
Do not be afraid to break things as that is perfectly normal. Troubleshooting and fixing code is perhaps the best booster for you to enhance your understanding of bash scripting and to improve your ability.
session
- kill seesion
screen -X -S [session # you want to kill] quit
- 新建screen会话 screen -S xxx
- 恢复指定会话 screen -r xxx
- 查看所有会话 screen -ls
- 删除指定会话 screen -S xxx -X quit
- 回到终端 Ctrl-a d
firewall
check status :
sudo ufw status
enable firewall:
1
2
3$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startupdisable firewall
1
2$ sudo ufw disable
Firewall stopped and disabled on system startup
磁盘相关
查看系统磁盘占用情况
df -h
查看目录下文件大小
du -sh
查看当前目录下一级子文件和子目录占用的磁盘容量:
du -h --max-depth=1
1
2
3
4
5查看当前目录下user目录的大小,并不想看其他目录以及其子目录:
du -sh user
-s表示总结的意思,即只列出一个总结的值
du -h --max-depth=0 user
--max-depth=n表示只深入到第n层目录,此处设置为0,即表示不深入到子目录。总结du常用命令
du -h –max-depth=1 |grep ‘G’ |sort #查看上G目录并排序
du -h –max-depth=1 |grep [TG] |sort #查找上G和T的目录并排序
du -sh –max-depth=1 #查看当前目录下所有一级子目录文件夹大小清理指定目录下的文件
例如需要根据时间删除这个目录下的文件,/tmp,清理掉20天之前的无效数据。可以使用下面一条命令去完成:
1
2
3
4
5
6
7
8find /tmp -mtime +21 -name "*" -exec rm -Rf {} \;
- /tmp :准备要进行清理的任意目录
- -mtime:标准语句写法
- +10:查找10天前的文件,这里用数字代表天数,+30表示查找30天前的文件
- "*":希望查找的数据类型,".jpg"表示查找扩展名为jpg的所有文件,""表示查找所有文件
- -exec:固定写法
- rm -Rf:强制删除文件,包括目录(注意R大写,f小写)
- {} \; 固定写法,一对大括号+空格+\+;
history
查看历史命令,支持 grep过滤操作
卸载安装的软件
1 | 浏览已安装的程序 dpkg --list |
安装deb文件出错时
使用apt-get -f -y install
修复之后,再进行安装
1 | 1.执行命令sudo dpkg -i XXX.deb 返回依赖关系错误提示 |
光标
1 | Ctrl+a:光标回到命令行首。 (a:ahead) |
时区
grep
限定查询结果之后的前几行 grep -m 10 <pattern> <file>
限定查询结果倒数的几行 grep <pattern> <file> | tail -10
日期
判断 day of year
doy=$(date +%j)
制定日期减一天
date -d"20140101 -1 days" +"%Y%m%d"
当前时间戳(秒)
1
date +%s
剪切板
将剪切板中的内容输出到文件 echo $(xsel –clipboard) >> a.txt
将文件的内容复制到剪切板 cat a.txt | xsel –clipboard
securtCRT
1 | 下载服务器文件 sz filename |
tr命令
tr – translate or delete characters
- 大小写转换
1
2cat file | tr A-Z a-z
cat file | tr a-z A-Z
top
“1”
查看所有CPU核的使用情况
“c”
查看具体进程的路径
1 | l- 开启或关闭第一部分第一行top信息显示 |
查看指定服务的运行情况
journalctl -u xxx.service
资源占用
1 | ps -aux | grep 服务名称或pid |
清理缓存
1 | sync; echo 1 > /proc/sys/vm/drop_caches |
centos安装离线依赖
1 | rpm -ivh name.rpm |