This has taken me quite a long time to figure out (being a beginner) , and now that I have, maybe some can show me or at least lead me to better way to do the same thing.
I have in ~/ a directory “A” with many sub directories, B, C, D, etc., within it. I want to tell if anything at all is inside the sub directories B, C, D, etc. I did this via an if statement.
All the work happens, the way I found it anyway, via this:
ls -R ~/A/*/* 2>/dev/null | grep -n ^/ | grep ^1
Starting with ls -R ~/A/*/*, it list everything inside of the sub-directories B,C,D, etc., which are in A. However, if they are all empty it gives an error message which in the end trips up the test condition for my if statement, [ condition ]. As a result I toss any error message into the world of nothingness via
ls -R ~/A/*/* 2>/dev/null
This works ok inside the test so long as there is not more than one item inside the sub-directories. For some reason the test thing does not seem to like to deal with multiple files and directories in this way. Thus I needed to get the output to list one and only one item, regardless of how many are in there. I have piped the output into “grep -n ^/”, which numbers the output, the output being anything that starts with “/” (and everything does as ~/ expands into /home/...). That still has many listings, but each starts with a number so I turned it into one listing by running grep that starts with the number 1, of which there should be at most only one listing, thus “grep ^1”.
At this point [ -n “$(X)” ] , where X is the above piped commands, expands into one and only one thing, if something at all is in the sub-directories, or into nothing “”, if the sub-directories are empty, thus [ -n “$(X)” ] expands into a 0 or a 1 based upon anything being in the sub-directories, and thus useful for an if statement, such as:
if [ -n "$(ls -R ~/A/*/* 2>/dev/null | grep -n ^/ | grep ^1)" ]; then
echo “something is in at least one folder”
echo "the folders are empty"
Now that seems like a lot to go through for what intuitively seems like it should be a very simple and basic thing to find out – is there stuff in those directories or is there not? My guess is that I have made it far more complex than needs to be – thus, if anyone knows a better way of going about all this please show me the simple way. Thanks