Shell 基础知识整理 01

常用又实用的 Shell 操作

1. 查看系统 Shell 的支持情况

# cat /etc/shells

2. 查看常用操作系统默认的 Shell

2.1 sample1
# echo $SHELL
2.2 sample2
# grep root /etc/passwd

3. 方便习惯 vi/emacs 的用户使用 vim

# echo "alias vi='vim'" >> /etc/profile
# source /etc/profile

4.Shell 脚本第一行的声明

#!/bin/bash

Shell 脚本在第一行会指出由哪个程序(解释器)来执行脚本中的内容,执行了相应解释器的位置。如果不是在顶端的第一行,则为脚本的注释行。

如果脚本文件中没有 #! 这一行, 那么它执行时会默认用当前 Shell 去解释这个脚本(即 $SHELL 环境变量)

5. bash 与 sh 的区别

[root@VM_153_220_centos ~]# ll /bin/sh
lrwxrwxrwx 1 root root 4 Sep 21 21:29 /bin/sh -> bash
[root@VM_153_220_centos ~]# ll /bin/bash
-rwxr-xr-x 1 root root 964544 Apr 11  2018 /bin/bash

早期的 bash 与 sh 有所区别,其还包括 csh 和 ksh 的特色。sh 为 bash 的软链接,在打多少股情况下,脚本的开头使用 #!/bin/bash#!/bin/sh 没有区别,但更规范的写法是在脚本开头使用 #!/bin/bash

比如,linux 下某些自带脚本的开头的声明

[root@VM_153_220_centos ~]# head -1 /etc/init.d/mysql 
#!/bin/sh
[root@VM_153_220_centos ~]# head -1 /bin/cd
#!/bin/sh
[root@VM_153_220_centos ~]# head -1 /etc/init.d/network 
#! /bin/bash

6. 查看系统的 bash 版本

[root@VM_153_220_centos ~]# cat /etc/redhat-release 
CentOS Linux release 7.5.1804 (Core) 
[root@VM_153_220_centos ~]# bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

7. 检测系统是否存在漏洞

# env x='() { :;}; echo be careful' bash -c "echo this is a test"
this is a test

如果返回以下两行, 则表示要尽快升级 bash,因为旧版的 bash 漏洞较多

be careful
this is a test

8. 升级 bash 方法

# yum -y update bash
# rpm -qa bash
bash-4.2.46-30.el7.x86_64

9. 常用脚本开头的写法

#!/bin/sh
#!/bin/bash
#!/usr/bin/awk
#!/bin/sed
#!/usr/bin/tcl
#!/usr/bin/expect
#!/usr/bin/perl
#!/usr/bin/env python

不同语言的脚本一般要加上相应的开头解释器语言标志。由于 CentOS 以及 Red hat linux 下的默认的 Shell 均为 bash。因此在写 Shell 脚本时,脚本不加 #!/bin/bash 也会交给 bash 解释。

如果脚本的第一行不指定解释器,就要用对应的解释器来执行脚本,只有这样才能确保脚本正常执行。例如:

  • Python 脚本,使用 python test.py 执行 test.py
  • Shell 脚本, 使用 bash test.sh 执行 test.sh

10. Shell 脚本执行的多种方式

  • bash script-name 或 sh script-name
  • path/script-name 或 ./script-name (可执行文件)
  • source script-name 或 .script-name
  • sh<script-name 或 cat script-name|sh

猜你喜欢

转载自blog.csdn.net/qq_36148847/article/details/83213504