【SXFU-云计算】Linux操作系统基础-Part7-Shell脚本基础

Shell 脚本

shell 语法概述

shell 脚本概念

  • shell脚本就是命令的集合

shell 语法概述 - 1

  • shell脚本是提高服务器管理维护的工具

shell 语法概述 - 2

shell 脚本使用基础

编写 shell 脚本

编写 shell  脚本-1

  • 赋予脚本first.sh执行权限:chmod +x first.sh

编写 shell  脚本-2

shell 脚本使用变量

  • shell中引用变量

 中引用变量

  • 数学运算

数学运算

  • 用户交互输入

用户交互输入

  • 脚本选项使用

脚本选项使用

shell 脚本使用判断

if 逻辑判断

  • shell中的逻辑判断

 中的逻辑判断

  • 逻辑表达式用 [ ] 括起来(注意 [ ] 前后的空格)

逻辑表达式用 [ ] 括起来(注意 [ ] 前后的空格)

  • 字符串判断

字符串判断

  • 文件判断

文件判断

编写shell脚本-3

编写shell脚本-4

编写shell脚本-5

  • 有bug:当分数输入为80时,会出现bug

小总结

  • 理解 shell脚本基础
  • 学会使用 shell脚本的基本变量
  • 学会使用 shell脚本的选项输入
  • 学会使用if判断
  • 理解 if 判断表达式

判断表达式

CASE 逻辑判断

CASE 逻辑判断-1

CASE 逻辑判断-2

CASE 逻辑判断-3

shell 中的循环

for 循环

  • 简单的 for 循环结构

for 循环-1

  • 系统命令的另一种调用

系统命令的另一种调用

while 循环

while 循环

上述 while 循环运行结果

until 循环

until 循环

shell 中的函数

shell 中的函数

shell 中的中断

break 中断

shell 中的中断

shell 中的中断-2

continue 中断

 continue 中断

 continue 中断 -2

exit 中断

exit 中断

exit 中断-2

Shell 脚本练习

1. 求和1-100

  • 任务描述

求和1-100

  • 第一种写法( for 写法)
1
2
3
4
5
6
7
8
9
# shell1.sh
# !/bin/bash
# Calculate the sum of numbers from 1 to 100
sum=0
for ((i=1; i<=100; i++))
do
sum=$((sum + i))
done
echo "The sum of numbers from 1 to 100 is: $sum"
  • 第二种写法( until 写法)
1
2
3
4
5
6
7
8
# !/bin/bash
i = 1
j = 0
until [ $i == 101 ]; do
j = $[ $i + $j ]
i = $[ $i+1 ]
done
echo "$j"

2. 求和1-n

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# shell2.sh
#!/bin/bash
# Calculate the sum of numbers from 1 to n, with input validation
while true; do
read -p "Enter a positive integer n: " n
if [[ $n =~ ^[0-9]+$ ]] && [ $n -ge 1 ]; then
break
else
echo "Invalid input. Please enter a positive integer."
fi
done

sum=0
for ((i=1; i<=n; i++))
do
sum=$((sum + i))
done
echo "The sum of numbers from 1 to $n is: $sum"
1
2
3
4
5
6
7
8
9
# !/bin/bash
n = 0
while [$n -lt "1" ]; do
read -p "Please input the number, it must greater than 1: " n
done
for i in `seq 1 $n`; do
sum =$[ $i + $sum ]
done
echo

3. 把 /root 目录下的所有目录(一级或多级)复制到 /tmp 目录下

1
2
3
4
5
6
7
8
9
10
11
12
13
# shell3.sh
#!/bin/bash
# Copy all directories from /root to /tmp
if [ -d /root ]; then
for dir in /root/*; do
if [ -d "$dir" ]; then
cp -r "$dir" /tmp
fi
done
echo "All directories from /root have been copied to /tmp."
else
echo "/root does not exist or is not a directory."
fi
1
2
3
4
5
6
# !/bin/bash
cd /root
for f in `ls`; do
if [ -d $f ]; then
cp -r $f /tmp/
done

4. 作业一个

4. 作业一个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
# 脚本提示用户输入喜欢的操作系统,并根据输入显示不同的消息

while true; do
read -p "请输入你喜欢的操作系统 (Windows, Mac, Linux): " os
case $os in
windows)
echo "你选择了Windows,这是一个广泛使用的操作系统。"
;;
mac)
echo "你选择了Mac,这是一个以易用性和设计著称的操作系统。"
;;
linux)
echo "真是伟大的选择!Linux是一个强大的开源操作系统。"
break
;;
*)
echo "输入无效,请重新输入。"
;;
esac
done
  • Copyrights © 2024-2025 brocademaple
  • 访问人数: | 浏览次数:

      请我喝杯咖啡吧~

      支付宝
      微信