#!/bin/bash
if(($#!=1))
then
echo "Please enter a file name: "
read f1
else
f1=$1
fi
while [ ! -f $f1 ]
do
echo "Please enter an existing file name: "
read f1
done
for file in *
do
if [ $file == $f1 ]
then
pwd
fi
echo "Check here 1"
done
for file in */*
do
if [ $file == $f1 ]
then
pwd
fi
echo "Check here 2"
done
這是我的腳本,我在包含該腳本的目錄中有檔案 f3.txt 和一個子目錄。
我想檢查這個檔案的位置。進入主目錄時,找到檔案時確實進入if成功,但進入子目錄時,即使f3.txt在子目錄下也不會進入if。
澄清一下,第一個 for 回圈作業得很好,當進入第二個 for 回圈時,它會根據子目錄中有多少檔案完美地在此處回顯檢查 2,但盡管有檔案 f3.txt,但不輸入 if在這個子目錄中
uj5u.com熱心網友回復:
直接的問題是通配符擴展為目錄名和檔案名,因此它當然不等于輸入檔案名。
if [ "$(basename "$file")" = "$f1" ]
在比較之前洗掉目錄名稱(并且還修復了參考和語法;字串相等比較運算子sh是=,雖然 Bash 也允許==作為同義詞,但我看不出有理由更喜歡它)
...雖然正確地說,你可能想要
find . -name "$f1" -maxdepth 2 -ls
或者-maxdepth 2如果您想遍歷子目錄的子目錄等,可以取出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449204.html
