Shell脚本无法识别用户输入的文件路径问题求助
问题:Shell脚本无法识别带
~的路径 我写了个批量移动INCAR、KPOINTS、openmpiscript、POSCAR和submit.vasp文件的Shell脚本,脚本会提示输入目标路径。但输入类似~/i/want/to/go/here的路径时(哪怕直接从命令行复制粘贴),明明路径真实存在,脚本却判定路径无效并退出。试了给$location加单/双引号、调整提示空格、反复核对路径都没用。
我的脚本代码如下:
I=INCAR K=KPOINTS o=openmpiscript P=POSCAR s=submit.vasp echo "we are going to move INCAR,KPOINTS,openmpiscript,POSCAR, and submit.vasp to a desired location" echo "Just tell me where to put them and I will automatically move all those files on your behalf." read -p "location please:" location echo "ok we can check and see whether or not $location is a real place" if [[ -d $location ]]; then echo "yup, $location is there" else echo "hmmm, this might not be a working directory path" exit 1 fi
原因
Shell里的~只有在未被引号包裹时才会被解析成用户主目录,但read命令默认不会自动展开~——输入的~/xxx会被当作字面量字符串处理,而不是转换成/home/你的用户名/i/want/to/go/here这样的真实路径,所以[[ -d $location ]]自然判断路径不存在。
解决方案
给路径加一步展开处理,把~转换成真实主目录路径,下面是两种可行方法:
方法1:手动替换~为$HOME(更安全)
如果担心后续风险,可以用字符串替换的方式处理:
在read命令之后添加一行代码:
location="${location/#\~/$HOME}"
方法2:用eval展开(适合自用脚本)
如果是自己使用的脚本,也可以用eval直接展开路径:
location=$(eval echo "$location")
修改后的完整脚本示例
I=INCAR K=KPOINTS o=openmpiscript P=POSCAR s=submit.vasp echo "我们要把INCAR、KPOINTS、openmpiscript、POSCAR和submit.vasp移动到指定位置" echo "告诉我目标路径,我会自动帮你移动这些文件。" read -p "请输入路径:" location # 处理~展开 location="${location/#\~/$HOME}" echo "现在检查$location是否存在" if [[ -d $location ]]; then echo "没问题,$location存在" # 这里可以添加移动文件的代码,比如: # mv "$I" "$K" "$o" "$P" "$s" "$location" else echo "哎呀,这个路径好像不存在" exit 1 fi
内容的提问来源于stack exchange,提问作者Calico Cat
相关产品推荐
相关产品推荐

