Ayush Kapil
Ayush Kapil

Reputation: 19

'find' command giving : No such file or directory error in shell script

I am writing a script to check the disk usage and list the files larger than 1MB in the path input by the user.

#!/bin/bash
DISK_USAGE=$(df -h /dev/xvda1 | awk '{gsub("%","");print $5}' | tail -1)

THRESHOLD=80

       
 if [ $DISK_USAGE -ge $THRESHOLD ]
 then

                read -p  "Enter the path for log files: " PATH
                echo "Below is the list of large log files which are taking space:"
                echo $("find $PATH -type f -size +1M")
 fi

Below is the output of this script:


Enter the path for log files: /var/log
Below is the list of large files which are taking space:
./sample-script.sh: line 17: find /var/log -type f -size +1M: No such file or directory

For some reason find command is not able to pick any path that I enter as an input.

What could be a possible reason and the solution?

Upvotes: 0

Views: 2810

Answers (1)

jhnc
jhnc

Reputation: 16662

    echo $("find $PATH -type f -size +1M")

This attempts to run a command called: find $PATH -type f -size +1M (with the $PATH expanded). As there is no such command you get the error.

Your quotes should be outside the $(...)

    echo "$(find $PATH -type f -size +1M)"

Better still, drop the echo as it is not required:

    find $PATH -type f -size +1M

As @alexcs notes, you shouldn't use PATH as a variable name because it is already used by the system (in fact you shouldn't use any all-caps variable name) and you should quote its use as the user may have provided something containing whitespace:

    read -p  "Enter the path for log files: " LogPath
    # ...
    find "$LogPath" -type f -size +1M

Consider:

echo $("echo '1..4..7'; echo 'a  b  c'")

"echo '1..4..7'; echo 'a  b  c'"

echo $(echo '1..4..7'; echo 'a  b  c')

echo "$(echo '1..4..7'; echo 'a  b  c')"

echo '1..4..7'; echo 'a  b  c'

Upvotes: 2

Related Questions