Script that displays contents of a directory

Hello all! I am writing a script that takes in a directory name as input and if the directory exists, it shows the files inside the directory

here is what I have so far (incomplete) (mostly like pseudocode)

#/bin/sh
echo Please enter the name of a directory
read dir
grep $dir /home/other/xxxxx
if test $? -eq 0
then
cd $dir ls (this is where I get confused, this is basically pseudo code to show what I am trying to do(
else
echo $dir is not a directory
fi

disregard the xxxxx, that is personal information I have erased. What I want it to do is use grep to search the current directory for any "sub directories" and see if they exist. If they do exist then run the cd command to jump to that directory and ls to show the contents. I am having trouble incorporating it into the script. Any help is appreciated. . thank you

grep matches strings inside files, not names of directories inside other directories.

You don't have to do

something
if [ $? -eq 0 ]
then

by the way, you can just do

if something
then
        echo something succeeded
else
        echo something failed
fi

...less chance of mixing up the value of $? that way.

You could just check whether the directory exists with [ -d ]:

read DIR
if [ -d /home/xxx/"$DIR" ]
then
        echo "$DIR exists in xxx"
        ls /home/xxx/"$DIR"
else
        echo "$DIR does not exist"
fi
1 Like

Similar to Corona688, but retaining and revising the question.

#/bin/sh
echo "Please enter the name of a subdirectory under /home/other"
read dir
if [ -d "/home/other/${dir}" ]
then
      ls -la "/home/other/${dir}"
else
      echo "Directory does not exist: /home/other/${dir}"
fi

See "man test" for the explanation of "if ... -d".

1 Like