How to check if a files exists in a specific directory in a bash script?

淺唱寂寞╮ 提交于 2019-12-30 04:59:05

问题


This is what I have been trying and it is unsuccessful. If I wanted to check if a file exists in the ~/.example directory

FILE=$1
if [ -e $FILE ~/.example ]; then
      echo "File exists"
else
      echo "File does not exist"
fi

回答1:


You can use $FILE to concatenate with the directory to make the full path as below.

FILE="$1"
if [ -e ~/.myexample/"$FILE" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi



回答2:


This should do:

FILE=$1
if [[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]]; then
      echo "File exists and not a symbolic link"
else
      echo "File does not exist"
fi

It will tell you if $FILE exists in the .example directory ignoring symbolic links.

You can use this one too:

[[ -e ~/.example/$FILE && ! -L ~/example/$FILE ]] && echo "Exists" || echo "Doesn't Exist"


来源:https://stackoverflow.com/questions/29927005/how-to-check-if-a-files-exists-in-a-specific-directory-in-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!