Linux | Shell脚本从入门到实战

之前在工作中经常有涉及到shell脚本的使用,也有在捞日志等场景下使用,但一直感觉知识不太系统化,遂在B站上找来尚硅谷的课程恶补一下~;

以下内容均来自尚硅谷视频课程笔记

一、Shell脚本入门

1. 脚本格式

指定解析器:脚本以 #!/bin/bash 开头

2. 脚本内容

创建shell脚本文件

[root@VM-0-3-centos LearnSource]# touch helloworld.sh
[root@VM-0-3-centos LearnSource]# vi helloworld.sh

脚本文件内容(输出helloworld)

#!/bin/bash

echo "helloworld"

3. 运行脚本

3.1 采用 bash / sh + 路径执行(不需要+x权限)

[root@VM-0-3-centos LearnSource]# sh helloworld.sh
helloworld
[root@VM-0-3-centos LearnSource]# bash helloworld.sh
helloworld

3.2 采用 ./路径执行 (需要可执行+x权限)

Linux的每个文件一般都有三个权限 r–读,w–写,x–执行,其分别对应的数值为4,2,1
777权限中的三个数字分别代表不同使用对象:User、Group、Other
修改权限使用 chmod xxx filename

  1. 赋予 helloworld.sh 脚本 +x 权限(777:可执行权限)
  2. 直接 ./ 执行脚本
[root@VM-0-3-centos LearnSource]# ./helloworld.sh
-bash: ./helloworld.sh: Permission denied
[root@VM-0-3-centos LearnSource]# chmod 777 helloworld.sh
[root@VM-0-3-centos LearnSource]# ./helloworld.sh
helloworld

二、Shell中的变量与运算符

1. 系统变量

  1. echo $HOME
  2. echo $PWD
  3. echo $SHELL
  4. echo $USER
[root@VM-0-3-centos LearnSource]# echo $HOME
/root
[root@VM-0-3-centos LearnSource]# echo $PWD
/data/LearnSource
[root@VM-0-3-centos LearnSource]# echo $USER
root
[root@VM-0-3-centos LearnSource]# echo $SHELL
/bin/bash

2. 自定义变量

2.1 基本语法

  1. 定义变量:变量=值
  2. 撤销变量:unset 变量
  3. 声明静态变量:readonly变量,注意:不能unset

2.2 变量定义规则

  1. 变量名称可以由字母、数字和下划线组成,但是不能以数字开头,环境变量名建议大写。
  2. 等号两侧不能有空格
  3. 在bash中,变量默认类型都是字符串类型,无法直接进行数值运算。
  4. 变量的值如果有空格,需要使用双引号或单引号括起来。

特殊的:可把变量提升为全局环境变量,可供其他Shell程序使用

升级为全局变量: export 变量名

[root@VM-0-3-centos LearnSource]# cat helloworld.sh
#!/bin/bash

echo "helloworld"
echo $B
[root@VM-0-3-centos LearnSource]# bash helloworld.sh
helloworld

[root@VM-0-3-centos LearnSource]# export B
[root@VM-0-3-centos LearnSource

你可能感兴趣的:(Linux,java,开发语言,后端,linux,shell)