개요

shell script 등을 작성할 때 특정 폴더내의 sub directory 를 순회하면서 특정 작업을 수행해야 하는 경우가 많이 있습니다.

ls 의 option 에는 directory 목록만 얻어오는 방법이 없으므로 ls 와 다른 command 를 사용해서 directory 목록을 얻어오는 방법을 정리해 봅니다


대상 폴더는 /target 이고 하위 directory 는 cs, draft, files, static 4개가 있다고 가정합니다.

방법

1.Using echo

$ echo target/*
target/cs target/draft target/files target/static
BASH

2.Using ls -d */

ls 의 directory 만 추출하는 옵션인 -d 를 사용합니다.

$ ls -d target/*
target/cs  target/draft  target/files  target/static
BASH

ls 의 출력 결과를 pipe 로 다른 프로그램과 연결할 경우 파일명 컬러 출력을 위한 ANSI Code 가 붙어서 제대로 처리가 불가능합니다. 이럴 경우 다음과 같이 --color=never 옵션을 붙여주면 됩니다.

ls --color=never -d target/*
CODE


3.Using ls and grep

$ ls -l target | grep "^d"
BASH
drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 cs
drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 draft
drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 files
drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 static
CODE

이제 awk 를 사용해서 9번째 필드를 출력하면 디렉터리이므로 이 결과를 다른 유틸리티에서 사용하면 됩니다.

$ ls -l |grep "^d"|awk '{print $9}'
CODE

4.Bash Script  사용

bash 에만 있는 기능을 이용하여 디렉터리만 추출할 수 있습니다.

경로명 맨 뒤에 / 로 끝나야 정상동작합니다.

$   for i in $(ls -d target/*/); do echo ${i%%/}; done 
target/cs
target/draft
target/files
target/static
BASH


shell script 에서 사용할 경우 취향에 따라 아무거나 골라써도 무난합니다.

shell script 예제

#!/bin/sh
 
DIRS=`ls -d target/*/`
 
for i in ${DIRS};do
      echo "Entering directory=$i";
      cd $i;
      cd ..;
done
BASH


Ref