Reputation: 887
I am trying to write a shell script, which checks if a given directory contains a particularly named subdirectory. I am passing the Parent directory as a first argument and only the name for the child directory. I want the script to go through the contents of the Parent and see if it contains a file of type directory, which is named with the name I am passing in for Child.
This is my code. In it I am trying to pipe the output of ls
on the Parent to the egrep
command. I am trying to write a regular expression that checks to see if the output of ls
has a name that matches (not identically. just somewhere in its name) my child name.
PARENT=$1
CHILD=$2
DIRNUM=$(ls -l $PARENT | egrep -c '< $CHILD >')
echo $DIRNUM
Upvotes: 3
Views: 13788
Reputation: 359
Use the find command like the following:
# find $parent -name \*${child}\* -and -type d
The type option is to insure that the found name is a directory.
This command will find all sub-directories located within $parent that contain $child in its name
Upvotes: 3
Reputation: 80921
Don't do this. Don't parse ls
.
Just check for the file/directory directly with the [
/test
built-in/command.
path=$parent/$child
if [ -d "$path" ]; then
echo "$path exists."
else
echo "$path does not exist."
fi
You'll note that I switched case on the variable names. ALL_UPPER variables are "reserved" for the shell's use you shouldn't use any.
Upvotes: 8