SoFunction
Updated on 2025-03-10

The shell obtains the names of all folders in the directory and outputs the instance

Get the names of all folders under the specified directory /usr/ and output:

Shell code:

#!/bin/bash
#Method 1dir=$(ls -l /usr/ |awk '/^d/ {print $NF}')
for i in $dir
do
 echo $i
done 
#######
#Method 2for dir in $(ls /usr/)
do
 [ -d $dir ] && echo $dir
done  
##Method Three
ls -l /usr/ |awk '/^d/ {print $NF}' ## In fact, the same method can be displayed directly without the for loop

After running the shell, the names of all folders in the /usr/ directory will be output:

[root@localhost ~]# ./
bin
etc
games
include
lib
lib64
libexec
local
sbin
share
src

The above example of the shell obtaining the names of all folders in the directory and outputting them is all the content I share with you. I hope you can give you a reference and I hope you can support me more.