I've searched high and low for a working answer but here I am, still stuck. I'm new to bash scripting and have spent the past few days trying to achieve my goal, but I'm losing my mind instead.
GOAL: I want to run a script that checks for directories that contains yesterday's date (date appears in between other text in the directory name). Sounds simple!
What I have so far:
DATE=$(date -d '1 day' %y%m%d)
ls /path/to/folders > ~/listofdirs.txt
GREPDIR=$(grep $DATE ~/listofdirs.txt)
if [ -d /path/to/folders/$GREPDIR ]; then
echo "Dir exists!"
echo "(cat $GREPDIR)"
exit 1
else
echo "Nothing found."
fi
Grep isn't finding any results as I am sure the $DATE isn't working as I expect. If I substitute $DATE with eg: 2022, I get a result. Thanks for any help, direction, advice.
CodePudding user response:
I suggest with bash
:
d=$(date -d '1 day' %y%m%d)
cd /path/to/folders || exit 1
if grep -q "$d" <<< *$d*; then
echo "found";
else
echo "not found";
fi
CodePudding user response:
You may simply use ls -d startsWith*
and check if the output is empty
as follows:
#!/bin/bash
dirsStartingWith="$(date -d '1 day ago' %y%m%d)*"
if [[ $(ls -d "$dirsStartingWith" 2>/dev/null) ]]; then
echo "there are folders starting with $dirsStartingWith"
#ls -d $dirsStartingWith # to test output
else
echo "no folders starting with $dirsStartingWith found"
fi
P.S. You may also use find
, but I think ls
should be sufficient as date
is contained in the name of folders.