Skip to content
Advertisement

Bash – how to exclude directory with find command and how to get full path with find?

so I have the code right now down below, and I’m running into a few problems with it

  1. I’m having trouble excluding the directories being outputted by

    find ${1-.}
    

    It is giving me the directories too instead of only names; I’ve tried different methods such as -prune etc.

  2. I’m having trouble with deleting the empty files

The data given to me by

    EMPTY_FILE=$(find ${1-.} -size 0)

Does not give me the correct path Here is the output for that

    TestFolder/TestFile

in this case I can’t just do:

    rm TestFolder/TestFile

As it is invalid path; since it needs ./TestFolder/TestFile

How would I add on the ./ or is there away to get the full path.

    #!/bin/bash

    echo "Here are all the files in the directory specifiedn"
    find ${1-.}

    EMPTY_FILE=$(find ${1-.} -size 0)
    echo "Here are the list of empty filesn"
    echo "$EMPTY_FILE n"
    echo "Do you want to delete those empty files?(yes/no)"
    read text
    if [ "$text" == "yes" ]; then $(rm -- $EMPTY_FILE); fi

Any help is appreciated!

Advertisement

Answer

You want this:

#!/bin/bash

echo -e "Here are all the files in the directory specifiedn"

# Use -printf "%fn" to print the filename without leading directories
# Use -type f to restrict find to files
find "${1-.}" -type f -printf "    %fn"

echo -e "Here are the list of empty filesn"

# Again, use -printf "%fn"
find "${1-.}" -type f -size 0 -printf "    %fn"

echo -e "Do you want to delete those empty files?(yes/no)"
read answer

# Delete files using the `-delete` option
[ "$answer" = "yes" ] && find "${1-.}" -type f -size 0 -delete

Also note that I’ve quotes "${1-.}" at all occurrences. Since it is user input, you can’t rely on the input. Even if it is a path, it might still contain problematic characters, like spaces.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement