簡體   English   中英

如何檢查文件是否存在於 bash 腳本的特定目錄中?

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

這是我一直在嘗試的,但沒有成功。 如果我想檢查 ~/.example 目錄中是否存在文件

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

您可以使用$FILE與目錄連接以創建完整路徑,如下所示。

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

這應該做:

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

它會告訴你$FILE存在於.example目錄中,忽略符號鏈接。

你也可以使用這個:

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

遲到了,但一個簡單的解決方案是使用 -f

if [[ ! -f $FILE]]
then
  echo "File does not exist"
fi

如果你好奇, 這里還有一些例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM