Bash 基础:脚本执行、引号与命令替换验证
1. 用途介绍
Bash 将命令组合为可重复执行的脚本,适用于文件处理、任务编排和运维自动化。本文区分解释器调用、直接执行、source 加载,并说明引号和命令替换的行为。
2. 准备运行环境
Linux Bash 普通账号即可,不需要 root 或网络。cat /etc/shells 查看列出的登录 Shell,bash --version 确认版本;/etc/shells 不等于系统全部已安装解释器清单。
3. 相关知识与注意点
• bash script.sh 通常不要求脚本可执行,但要可读取;./script.sh 需要执行权限和正确 shebang。
• sh script.sh 使用 sh,不保证支持 Bash 扩展语法。
• source script.sh 或 . ./script.sh 在当前 Shell 执行,可能修改当前变量、目录或直接 exit;只加载可信文件。
• 单引号保留字面内容,双引号允许变量和命令替换;无引号会发生分词和通配符展开。
• $(...) 比反引号更易嵌套;会去掉捕获输出的末尾换行。不要解析 ls 输出做通用文件名列表。
• Bash 变量通常保存字符串,也支持整数等属性,不能把所有 Shell 一概描述为同一类型系统。
4. 实验步骤
bash
name='demo value'
printf '%s\n' '$name' "$name"
result=$(printf 'hello\n')
printf '<%s>\n' "$result"
预期依次显示字面 $name、demo value、<hello>。示例为预期值,不是本机执行报告。
保存为 demo.sh:
bash
#!/usr/bin/env bash
printf 'hello from Bash\n'
bash
bash -n demo.sh
bash demo.sh
chmod u+x demo.sh
./demo.sh
前两种执行不把子进程中的普通变量修改自动传回父 Shell;source 行为不同。
5. 原实验截图


6. 验证与快捷键
用 bash -n 检查语法后再执行,比较两次 hello 输出。交互式 Bash 默认 Emacs 编辑模式下,Ctrl+A/E 到行首/尾,Ctrl+U/K 删除部分命令,Ctrl+Y 粘回,Ctrl+L 清屏;其他键位模式可能不同。脚本不需要服务端口或 systemctl 验证。