Bash: exit a script when a specified folder is empty via the find command

bash check if directory is not empty
bash check if directory contains specific file
unix command to check if any file exists in a directory
bash if
bash check if directory contains files
bash check if directory exists
bash check if directory has subdirectories
makefile check if directory is empty

I want to check whether a folder is empty. If yes, write a log file and exit the script.

My code is below:

find $folder -maxdepth 0 -empty -exec echo [`date`] $folder is empty > log.txt & exit 0 \;

However, I received that

find: missing argument to `-exec'

Could you please help me to figure out the problem?




Thanks for all of you!

I just tried only to exit the script without output log:

find $folder -maxdepth 0 -empth -exec exit 0 \;


find $folder -type d -empty -exec exit 0 \;

I received error:

find: ‘exit’: No such file or directory

And the script keeps running even I have put set -e at the top of the script. I have no idea how to fix it.

If I understand the question correctly, this should work:

if find "$folder" -maxdepth 0 -empty | grep -q "."; then
    echo "[$(date)] $folder is empty" > log.txt    # Should this be >> to append?
    exit 0

Explanation: if the directory $folder is empty, the find command prints its path; grep checks to see whether it got anything ("." is a pattern that matches any character), and exits with a success status if there was a match; the if statement then runs or skips its content based on grep's exit status.

Explanation of why the original didn't work: the command in -exec is not a full shell command, it's just a series of words that're going to be passed to the execl() system call (or a related function). That is, it's a filename of an executable (to be found in the usual PATH) followed by a list of arguments to be passed to it.

This has two important implications: you can't use any shell features in the command, so no redirects (> log.txt), no multiple commands joined by & or ; or | or anything like that, no variable substitutions, etc. In the case of your command, all of those things will get parsed by the shell before passing the result to find -- so the redirect to log.txt happens to the entire find command, the date substitution happens before find is run, the & puts the find command in the background and treats the part after as a completely different command.

Furthermore, exit is not a regular command that can be run with execl() or such; it's a shell builtin (try type -a exit), and so it cannot be executed by -exec. And even if it could, it wouldn't do what you want, because the command run by -exec is run as a subprocess, and it would just exit that subprocess, not the entire script (or even the find command).

Bash Shell Check Whether a Directory is Empty or Not, How can I check from bash/ksh shell script if a directory contains files? [ donotprint][/donotprint]In this example, find command will only print file name from /tmp. $0 dir-name"; exit 1; } # Check for empty files using arrays chk_files= (${1}/*)� Check if folder /data/ is empty or not using bash only features. From the Linux and Unix bash(1) man page: nullglob If set, bash allows patterns which match no files to expand to a null string, rather than themselves.

Like this, no need find -maxdepth 0 :


shopt -s dotglob # enable globing even with .hidden files

for dir in */; do
    if ! stat $dir/* &>/dev/null; then 
        echo "[$(date)] $dir is empty" | tee log.txt

Bash scripting: test for empty directory, if find /some/dir -mindepth 1 | read; then echo "dir not empty" else echo "dir empty " fi at a directory entry via "-maxdepth 0" and test if it is empty with "-empty". Applied -maxdepth 0 -empty)" ; then echo "No new file" exit 1 fi or the same command split on three lines just to be more readable: IN , considering script is in . ./script /etc Sample outputs: /etc not empty. Create a directory / folder called /tmp/foo using mkdir command: $ mkdir /tmp/foo Run the script as follows:./script /tmp/foo Sample outputs: /tmp/foo empty. Method #2: Other commands. See our previous tutorial and comments for more info: Bash Shell Check Whether a Directory is Empty or Not

I think (now) you want the following:

# Exit if the current folder is empty
if [ $(find "${folder}" -maxdepth 0 -empty | wc -c) -gt 0 ] ; then
    printf "[%s] %s is empty\n" "$(date)" "${folder}" >> log.txt
    exit 0

Script to monitor folder for new files?, You should consider using inotifywait , as an example: Also, your read command can assign the positional output into multiple just to check if the folder is still empty, in fact it will return a 0 if there is no new file shell scripts from masking signals. entr waits for the utility to exit to ensure that Bash cannot do this easily. Check your spelling of empty, but then also try this: #!/bin/bash -e if [ -s diff.txt ] then rm -f empty.txt touch full.txt else rm -f full.txt touch empty.txt fi I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.

Try with a {} +

like this

find $folder -maxdepth 0 -empty -exec echo [`date`] $folder is empty {} + > log.txt & exit 0

Shell script to check for the presence of one or more files with a , Stephane Chazelas' great answer to How to stop the find command after first match? the nullglob option so that a wildcard that matches no file expands to an empty list. #!/bin/bash shopt -s nullglob csv_files=(/home/Savio/Dsktop/check/* .csv) Note that it looks for files regardless of their type (regular, directory, symlink,� Bash Shell Find Out If a Variable Is Empty Or Not. Let us see syntax and examples in details. The syntax is as follows for if command: if [ -z "$var" ] then echo "\$var is empty" else echo "\$var is NOT empty" fi. if [ -z "$var" ] then echo "\$var is empty" else echo "\$var is NOT empty" fi. OR.

Bash Commands to Manage Directories and Files, Learn how to run useful Bash commands to access and manage to another directory; easily create new files using a single command It is typically printed as the full path to the directory (meaning that you can see the parent directory). To delete a specific file, you can use the command rm followed by� If the line is empty, WORDS and the prompt are redisplayed. If EOF (end of file) is read, the command completes. The loop continues until a break (CTRL+C) is encountered. Example. Create a shell script called

Working With Files and Directories – The Unix Shell, Delete, copy and move specified files and/or directories. Let's go back to our data-shell directory on the Desktop and use ls -F to see what it contains: Let's create a new directory called thesis using the command mkdir thesis (which has Once our file is saved, we can use Ctrl + X to quit the editor and return to the shell. Note that not all shells will wait for that find command after head has returned. The Bourne shell and AT&T implementations of ksh (when non-interactive) and yash (only if that pipeline is the last command in a script) would not, leaving it running in background. If you'd rather see that behaviour in any shell, you could always change the above to:

How To Check If File or Directory Exists in Bash – devconnected, Check if file or directories exists in Bash using Bash tests and shorter forms. Based on this condition, you can exit the script or display a warning simply check if it exists using the “-f” flag and specify the command to run if it� You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data. This page shows how to check if a file is empty in Bash shell running on a Linux or Unix-like operating systems.

  • & is a command separator. Your shell is running find $folder -maxdepth 0 -empty -exec echo [`date`] $folder is empty as one command (in the background because it's terminated by &), with its output directed to log.txt, and exit 0 \; as a second, separate command. Because there's no ; or {} + following -exec as part of the same command... well, there's your problem.
  • Remove the & exit 0 part.
  • exit is built into the shell. It's not an external command. find is not a part of the shell, so it has no access to shell builtins; it can only run commands that have their own separate executables (and these commands, because they're run as independent executables, can't change the shell's own state -- can't set variables in it, or tell it to exit, or so forth).
  • Thanks for your solution. It works for my purpose and helps me understand the issue. :)
  • What does the OP expect the exit 0 to do? If they expect it to cause find to stop processing additional files, they're going to be surprised.
  • It's not an idea but a real implementation of your needs. Advice to newcomers: If an answer solves your problem, please accept it by clicking the large check mark (✓) next to it and optionally also up-vote it (up-voting requires at least 15 reputation points). If you found other answers helpful, please up-vote them. Accepting and up-voting helps future readers. Please see the relevant help-center article
  • Yes! But I am also looking for exiting the script.
  • find $folder -maxdepth 0 -empty -exec echo [date] $folder is empty {} + > log.txt & exit 0 The last part \; was giving the error
  • I tried several ways, but I cannot fix this issue. Any suggestion? Thx!
  • have you declared the variable folder with the name of an empty folder?