创建一个.sh 脚本文件

编辑

centos sh 执行权限 centos怎么执行sh文件_文件名

// An highlighted block
#!/bin/bash
echo “hello.world”

执行

centos sh 执行权限 centos怎么执行sh文件_文件名_02

shell定义变量以及引用

centos sh 执行权限 centos怎么执行sh文件_linux_03

变量定义

centos sh 执行权限 centos怎么执行sh文件_shell_04

// An highlighted block
变量的定义使用  	A=100 
输出  echo "A=$A"
消除变量A     unset A
定义静态变量 readonly A=99    注:静态变量不能被unset

赋值语句代码如下

// An highlighted block
A='ls -l'
或
A=$(ls -l)
# 运行‘’里面的命令 并把返回的结果值传给变量A
位置参数变量

centos sh 执行权限 centos怎么执行sh文件_centos sh 执行权限_05


具体应用示例

centos sh 执行权限 centos怎么执行sh文件_for循环_06

Shell 预定义变量

centos sh 执行权限 centos怎么执行sh文件_linux_07

Shell 运算式

第一种用字母等运算式

centos sh 执行权限 centos怎么执行sh文件_shell_08


第二种用符号运算式

// An highlighted block
Result=[(2+3)*4]
echo "结果=$Result"
判断语句
-lt     小于
-le    小于等于
-eq     等于
-gt     大于
-ge   大于等于
-ne    不等于
-r    判断文件是否有读权限
-w    判断文件是否有写权限
-x    判断文件是否有执行权限
-f     判断文件存在,并且是一个常规文件
-e     文件存在
-d     文件存在 ,并且是个目录

以上配合(if 、 elif 、then 、 fi 判断语句)

演示案例:

centos sh 执行权限 centos怎么执行sh文件_centos sh 执行权限_09


案例二

centos sh 执行权限 centos怎么执行sh文件_centos sh 执行权限_10


案例三 判断文件是否存在

centos sh 执行权限 centos怎么执行sh文件_for循环_11

Case 案例

centos sh 执行权限 centos怎么执行sh文件_for循环_12

For循环控制流程

第一类for循环的两种案例(for in 一个对象)

centos sh 执行权限 centos怎么执行sh文件_linux_13


第二类常规 for循环

centos sh 执行权限 centos怎么执行sh文件_shell_14


注意计算式改为如下

// An highlighted block
SUM=$[$SUM+$i]
read 读取控制台的输入

centos sh 执行权限 centos怎么执行sh文件_文件名_15


案例:

centos sh 执行权限 centos怎么执行sh文件_文件名_16

系统内置常用函数

centos sh 执行权限 centos怎么执行sh文件_for循环_17


案例

centos sh 执行权限 centos怎么执行sh文件_shell_18


第一句中 没有设置suffix 可以看到, 结果是把文件名+后缀名返回

第二句中【开启suffix】(,txt)可以看到返回的只有文件名会把文件的的后缀去掉。函数二 dirname (是返回文件路径的函数)

案例

centos sh 执行权限 centos怎么执行sh文件_centos sh 执行权限_19

自定义函数

自定义函数格式如下图所示

centos sh 执行权限 centos怎么执行sh文件_shell_20


一般来讲 shell中的函数不需要传参

案例一

centos sh 执行权限 centos怎么执行sh文件_文件名_21