shell

1、编写shell脚本的格式

```bash
#!/bin/bash
# 指定解析器

# 注释

1、编写一个脚本,实现创建100个txt文件

#!/bin/bash

touch {1..100}.txt
```

2、运行脚本的几种方式

```bash
方式一:绝对路径(运行的脚本必须有可执行权限)

方式二:相对路径(运行的脚本必须有可执行权限)

方式三:解释器 + 文件路径(不需要可执行权限)
```

3、变量

```bash
定义一个变量,令其等于1+1

num = `echo "1+1" | bc`

例1:探测当前系统所处于的网段中,有哪些IP可用
[root@localhost ~]# for i in {1..255}; do
ping -c1 -t1 192.168.230.$i &>/dev/null;
if [ $? -eq 0 ];then
echo "192.168.230.$i";
fi;
done

 

# 系统预定义变量

$* : 所有的参数
$@ : 所有的参数
$$ : 当前脚本的进程PID
$# : 当前脚本的参数个数
$? : 当前进程执行的状态


例2:编写一段脚本,实现计算器功能
[root@localhost ~]# cat calc.sh
#!/bin/bash
NUM1=$1
NUM2=$3
JISUAN=$2
echo "$NUM1 $JISUAN $NUM2 = "`echo "$NUM1 $JISUAN $NUM2"|bc`


例3:编写一个脚本,实现登录功能

read -p "请输入用户名:" username
read -p "请输入密码:" password
if [[ $username == "admin" && $password == '123']];then
echo "登录成功"
else
echo "用户名密码错误"
fi
```

4、数组

```bash
- 普通数组:只能使用整数作为数组索引
- 关联数组:可以使用字符串作为数组索引,需要用declare -A声明

声明数组

普通数组
[root@localhost ~]# declare -a arr

关联数组
[root@localhost ~]# declare -A array

赋值的方式

方式1:定义赋值
[root@localhost ~]# declare -a arr=("xiaohua" "nv" "45")

方式2:变量式赋值
[root@localhost ~]# arr[3]=ShangHai

方式3:利用命令赋值
[root@localhost ~]# arr=(`ls /root`)

取值的方式
1、使用下标的方式
[root@localhost ~]# echo ${array[1]}

2、反向取值
[root@localhost ~]# echo ${arr[-1]}

3、取出所有的值
[root@localhost ~]# echo ${arr[*]}

注:正向取值从零开始,反向取值从负一开始

遍历数组
#!/bin/bash

declare -a arr=(`ls /root`)

for i in ${arr[*]}
do
echo $i
done

例4:统计etc目录下,文件中写了多少个root
[root@localhost ~]# grep -oR 'root' /etc/ | grep -v 'Binary' | wc -l
#!/bin/bash
declare -A arr
NUM=`grep -oR 'root' /etc/ | grep -v 'Binary' | awk -F: '{print $NF}' `
for i in $NUM
do
if [[ ${arr[$i]} == '' ]];then
arr[$i]=0
fi
num=${arr[$i]}
arr[$i]=`echo "$num+1"|bc`
done
echo ${arr[*]}

 

例5:计算/etc/password 下每一个词各有多少个

 

xx=123
let num=xx+1 124

let num=xx++ 123

let num=++xx 124

xx++ 等价于 xx + 1 (先赋值,后加减)
xx--

++xx 等价于 xx + 1 (先加减,后赋值)
--xx


while true
do
let x++
let num+=x
if [ $x -eq 100 ];then
break;
fi
done

```

 

 

 

 

 

 

 

posted @   甜甜de微笑  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示