質問

I am just starting to learn bash script and have a question that I cannot find an answer to. I am currently in a directory called lab2. Inside this directory I have another directory "students" which contains directories named after each student's netid. Like ~/lab2/students/johndoe. So there are many directories inside students. My script is located inside the lab2 directory and I need to write a script to print out the names of directories inside students directory ( and of course I need to use relative paths).... How do I do that? I tried a few thing, one of which is

$MYDIR="$PWD/students"

DIRS=`ls -l . | egrep '^d' | awk '{print $8}'`

for DIR in $DIRS    
do    
    echo  ${DIR}    
done

but it did not work.... thank you!

役に立ちましたか?

解決 2

$MYDIR="$PWD/students"

but it did not work...

That's no wonder - the correct syntax is

MYDIR="$PWD/students"

(without leading $).

他のヒント

Check if following helps:

find ~/lab2/students -type d -maxdepth 1

And in case you want the directory(students name) names only:

find ~/lab2/students -maxdepth 1 -type d  | awk -F/ '{print $NF}'

Please read man page of find, it will help a lot.

awk -F/ '{print $NF}' is filtering the last field.

And in case you want to something with those directory names in your bash script you can do something like:

#!/bin/bash

for file in $(find ~/lab2/students -maxdepth 1 -type d) #or you can use the awk one here
do

echo $file
#your stuff here

done

Expanding on @Jord's answer, you can use find with some options to get some very fine grained control over the output:

  • -mindepth and -maxdepth control the recursion depth (which is 0-infinite by default).
  • -type d lists only directories.
  • -printf %f prints the name of the directory (or file, or symlink, etc.) without the leading directories.

man find has more information, and info --raw-escapes --subnodes find | less --raw-control-chars has full details.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top