📖 知识点
1. Windows 批处理 → Linux 脚本
| Windows | Linux | 说明 |
|---|---|---|
| .bat 批处理 | .sh bash 脚本 | 把多条命令存进文件 |
| 双击运行 |
| 执行脚本 |
脚本(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运行。
⚠️ 易错提醒
脚本第一行写
#!/bin/bash,告诉系统用什么解释器用
./脚本.sh运行前,先chmod +x加执行权限想省事就用
bash 脚本.sh,不用管执行权限
⚔️ Kata 实战任务
任务需求:
用 vim(或 echo)创建脚本文件
hello.sh第一行写
#!/bin/bash,下面写一句echo "你好,Linux!"用
bash hello.sh运行,看到输出再用
chmod +x+./hello.sh方式运行体会两种运行方式
参考代码(在终端依次敲)
# 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!
💡 完成动作示意:
vim hello.sh→ 输入#!/bin/bash和echo "你好,Linux!"→:wq保存
bash hello.sh输出 "你好,Linux!"
chmod +x hello.sh加执行权限 →./hello.sh同样输出
🧠 思考题
脚本第一行
#!/bin/bash起什么作用?能不能省略(用bash 脚本.sh运行时)?bash hello.sh和./hello.sh两种运行方式的区别是什么?后者为什么需要chmod +x?