如何在Bash加密解密脚本中支持用户输入带路径的文件名?
解决文件加密解密脚本支持带路径文件名的问题
你的脚本本质上已经可以处理带路径的文件名,只需修正几个细节并添加健壮性检查,就能完美支持任意路径的文件操作:
核心修改点
- 修复拼写错误(
Dcryption→Decryption) - 用引号包裹文件名变量,避免路径含空格或特殊字符时出错
- 添加文件存在性校验,防止处理不存在的文件
- 统一变量命名,简化代码逻辑
修改后的完整脚本
#!/bin/bash echo "This is a simple file encrypter and decrypter" echo "Please choose what you want to do: " choice="Encrypt Decrypt" select option in $choice; do if [ "$REPLY" = 1 ]; then echo "You have selected Encryption" echo "Please enter the file name (supports full/relative paths):" read -r file # 检查文件是否存在 if [ ! -f "$file" ]; then echo "Error: File '$file' does not exist!" continue fi gpg -c "$file" echo "The file '$file' has been encrypted" else echo "You have selected Decryption" echo "Please enter the encrypted file name (supports full/relative paths):" read -r file if [ ! -f "$file" ]; then echo "Error: File '$file' does not exist!" continue fi # 解密后自动生成原文件名(去除.gpg后缀) gpg -d "$file" > "${file%.gpg}" rm "$file" echo "The file has been decrypted to '${file%.gpg}'" fi done
关键细节说明
"$file"包裹变量:确保路径中的空格、特殊字符被正确识别read -r:避免反斜杠被当作转义字符处理,保证路径输入准确- 文件存在性检查:提前拦截无效输入,避免gpg执行报错
- 解密自动命名:默认生成去掉
.gpg后缀的原文件,也可根据需求调整为其他输出方式
修改完成后,用户即可输入任意相对路径或绝对路径的文件名进行加密解密操作。
内容的提问来源于stack exchange,提问作者sidharth panda
相关产品推荐
相关产品推荐

