如何在Bash脚本中创建临时文件测试用户输入文件是否存在?
如何测试你的Bash文件存在判断脚本
嘿,我来帮你搞定测试的事儿!先给你提个小细节:你脚本里的Read得改成小写的read,Bash对命令大小写敏感,大写的话会被识别成未知命令哦~
先修正基础脚本
修正后的可运行基础版本:
#!/bin/bash # Ask user for filename read -p "Enter a filename: " file # See if file exists if [ -f "$file" ] then echo "$file found" else echo "$file not found" fi
一步步教你测试
1. 保存脚本文件
把上面的代码保存成一个文件,比如命名为file_checker.sh。
2. 给脚本添加执行权限
打开终端,运行这条命令让脚本可以直接执行:
chmod +x file_checker.sh
3. 测试不同场景
场景1:测试存在的文件
- 先用你猜到的
touch命令创建一个临时测试文件:touch my_test_file.txt - 运行脚本:
./file_checker.sh - 输入
my_test_file.txt回车,就能看到my_test_file.txt found的提示啦。
场景2:测试不存在的文件
- 直接运行脚本,输入一个不存在的文件名(比如
this_file_doesnt_exist.txt),回车后会得到this_file_doesnt_exist.txt not found的反馈。
场景3:测试系统自带文件
可以试试输入系统里肯定存在的文件路径,比如/etc/passwd,脚本会返回它存在的提示;或者输入/tmp/random_nonexistent_file,会提示文件不存在。
额外的新手友好优化(可选)
你可以给脚本加个空输入判断,避免用户直接回车导致的错误:
#!/bin/bash # Ask user for filename read -p "Enter a filename: " file # 检查用户是否输入了内容 if [ -z "$file" ]; then echo "⚠️ 错误:你没有输入文件名!" exit 1 # 退出脚本,返回错误码 fi # See if file exists if [ -f "$file" ] then echo "$file found" else echo "$file not found" fi
内容的提问来源于stack exchange,提问作者yes indeed
相关产品推荐
相关产品推荐

