Shell脚本参数处理与默认值设置全解析
1. 变量引用加引号的重要性
在Shell脚本中,处理带空格的文件名时,引号的使用至关重要。下面通过几个示例来说明不同情况下引号的作用。
- 示例一:未加引号的文件名调用脚本
bash $ cat simpls.sh # simple shell script ls -l ${1} $ $ ./simple.sh Oh the Waste ls: Oh: No such file or directory
当调用脚本时未给文件名加引号, bash 会将其解析为三个参数,并将第一个参数 Oh 替换 $1 。 ls 命令以 Oh 作为唯一参数,自然找不到该文件。
- 示例二:调用脚本时文件名加引号,但脚本内变量引用未加引号
bash $ ./simpls.sh "Oh the Waste" ls: Oh: No such file or directory ls: the: No such file or directory ls: Waste: No such file or directory
虽然调用脚本时文件名加了引号,但脚本内变量引用 ${1} 未加引号, ls 会将每个单词视为单独的参数,同样找不到文件。
- 示例三:脚本内变量引用加引号 </
超级会员免费看
订阅专栏 解锁全文
931

被折叠的 条评论
为什么被折叠?



