Home > Back-end >  searching for a file name in a directory and all its subdirectories not recognizing the file in the
searching for a file name in a directory and all its subdirectories not recognizing the file in the

Time:03-24

#!/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

This is my script, and I have the file f3.txt in the directory having this script and a subdirectory in it.

And I want to check where this file is located. when entering the main directory, it does enter the if successfully when they find the file, but when entering the subdirectory, it won't enter the if even though f3.txt is in the subdirectory.

To clarify, the first for loop works perfectly fine, when entering the second for loop, it does echo check here 2 perfectly according to how many files there is in the subdirectory, but doesn't enter the if despite having a file f3.txt in this subdirectory

CodePudding user response:

The immediate problem is that the wildcard expands to the directory name and the file name, and so of course it will not be equal to just the input file name.

if [ "$(basename "$file")" = "$f1" ]

strips the directory name before comparing (and also fixes quoting and syntax; the string equality comparison operator in sh is = and although Bash also allows == as a synonym, I can see no reason to prefer that)

... though properly speaking, you probably want

find . -name "$f1" -maxdepth 2 -ls

or maybe take out -maxdepth 2 if you want to traverse subdirectories of subdirectories etc.

  • Related