绝技三"自动化内功"-Day37|内力初凝:什么是脚本,创建第一个 bash 脚本

25 次阅读 2026-10-28 11:44

📖 知识点

1. Windows 批处理 → Linux 脚本

 

 

WindowsLinux说明
.bat 批处理.sh bash 脚本把多条命令存进文件
双击运行

bash 脚本.sh 或 ./脚本.sh

执行脚本

脚本(script):把一串命令按顺序写进一个文件,执行时一次全跑。适合重复操作、批量任务,是自动化的基础。

💡 生活比喻手工一个个放鞭炮麻烦,脚本就像 "把一串鞭炮的引线接在一起"—— 点一次(运行脚本),整串(所有命令)就按顺序全响(全执行)。

2. 脚本的第一行:shebang

 

#!/bin/bash

 

写在脚本第一行,告诉系统 "用 bash 来执行这个脚本"。这叫 shebang(井号 + 感叹号)。

3. 写一个最简单的脚本

 

# 创建脚本文件
touch hello.sh
# 写入内容
echo '#!/bin/bash' > hello.sh
echo 'echo "你好,Linux!"' >> hello.sh

 

或直接用 vim:

vim hello.sh

 

内容:

#!/bin/bash
echo "你好,Linux!"

 

4. 运行脚本的两种方式

 

# 方式1:直接调bash执行(不用加执行权限)
bash hello.sh

# 方式2:先加执行权限,再直接运行(Day16学过chmod)
chmod +x hello.sh
./hello.sh

 

方式 1 最省事:bash 脚本.sh;方式 2 更 "正式":加 x 权限后用 ./脚本.sh 运行。

⚠️ 易错提醒

  1. 脚本第一行写 #!/bin/bash,告诉系统用什么解释器

  2. 用 ./脚本.sh 运行前,先 chmod +x 加执行权限

  3. 想省事就用 bash 脚本.sh,不用管执行权限

⚔️ Kata 实战任务

任务需求:

  1. 用 vim(或 echo)创建脚本文件 hello.sh

  2. 第一行写 #!/bin/bash,下面写一句 echo "你好,Linux!"

  3. 用 bash hello.sh 运行,看到输出

  4. 再用 chmod +x + ./hello.sh 方式运行

  5. 体会两种运行方式

参考代码(在终端依次敲)

 

# 1. 创建脚本(用vim编辑)
vim hello.sh
#   内容:
#   #!/bin/bash
#   echo "你好,Linux!"
#   (:wq 保存退出)

# 2. 用bash方式运行
bash hello.sh

# 3. 加执行权限,用./方式运行
chmod +x hello.sh
./hello.sh

 

运行示例:

 

user@linux:~$ bash hello.sh
你好,Linux!

user@linux:~$ chmod +x hello.sh
user@linux:~$ ./hello.sh
你好,Linux!

 

💡 完成动作示意:

  1. vim hello.sh → 输入 #!/bin/bash 和 echo "你好,Linux!" → :wq 保存

  2. bash hello.sh 输出 "你好,Linux!"

  3. chmod +x hello.sh 加执行权限 → ./hello.sh 同样输出

🧠 思考题

  1. 脚本第一行 #!/bin/bash 起什么作用?能不能省略(用 bash 脚本.sh 运行时)?

  2. bash hello.sh 和 ./hello.sh 两种运行方式的区别是什么?后者为什么需要 chmod +x?