shell判断语句if[ -e ]的坑

Endless_daydream Lv4

环境:ubuntu22.04, zsh,脚本使用#!/bin/bash

问题:

1
2
3
if [ -e $file_name ]; then 
dosomething
fi

以上代码在file_name变量未定义的时候将进入判断语句内部,也就是[ -e ] 会返回0(成功),这可能导致意想不到的后果。

解决方法:

用””包裹$file_name,即[ -e "" ] 会像预期一样返回1

这个坑是我改别人的shell脚本来用的时候遇到的,代码里没有用””包裹变量,我修改变量名字忘了改这里,触发这个坑。结果sudo rm -rf了我的一个仓库,里面还有未push的进度,哭。

  • Title: shell判断语句if[ -e ]的坑
  • Author: Endless_daydream
  • Created at : 2024-03-04 21:49:24
  • Updated at : 2024-03-04 22:01:44
  • Link: https://endless_daydream.gitee.io/2024/03/04/shell/shell遇坑记录/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
shell判断语句if[ -e ]的坑