IT/리눅스

[Linux] 디렉토리 삭제 방법, rmdir 명령어 사용 방법

몬스터r 2022. 12. 26. 09:00

[Linux] 디렉토리 삭제 방법, rmdir 명령어 사용 방법

오늘은 디렉토리 삭제 방법에 대해 알아보겠다. 디렉토리를 삭제하는 명령어는 두 개로 나눌 수 있는데, 하나는 rmdir, 하나는 rm 명령어다.

 

rm 명령어는 파일 삭제하는 명령어가 아닌가요? 라고 의문이 들 수 있는데, rm 명령어에서 옵션만 사용하면 rmdir보다 쉽게 파일을 삭제할 수 있기 때문에 필자는 rm 명령어를 주로 사용한다.

 

 

디렉토리 삭제 방법


rmdir 명령어 사용

--ignore-fail-on-non-empty '비어있지 않은 디렉토리를 삭제할 수 없다'는 메시지 무시
-p / --parents 상위 디렉토리 지정 시 상위 디렉토리도 함께 삭제
-v / --verbose 삭제되는 과정을 자세히 출력
--version rmdir 버전 출력

 

  • --ignore-fail-on-non-empty 옵션 사용
[haechan@haechan ~/diroec]$ ll test3
total 0
drwxrwxr-x. 3 haechan haechan 18 Dec 24 17:28 test3

[haechan@haechan ~/diroec]$ rmdir test3
rmdir: failed to remove ‘test3’: Directory not empty
# 에러 메시지 출력

[haechan@haechan ~/diroec]$ rmdir --ignore-fail-on-non-empty test3
# 에러 메시지 무시

[haechan@haechan ~/diroec]$ ll test3
total 0
drwxrwxr-x. 3 haechan haechan 18 Dec 24 17:28 test3

 

  • -p 옵션 사용
[haechan@haechan ~/diroec]$ ll test3
total 0
drwxrwxr-x. 3 haechan haechan 18 Dec 24 17:28 test3

[haechan@haechan ~/diroec]$ rmdir -p test3/test

[haechan@haechan ~/diroec]$ ll test3
ls: cannot access test3: No such file or directory

--ignore-fail-on-non-empty 옵션 예제에서는 상위 디렉토리인 test 때문에 에러가 발생하며 삭제가 안 되었지만, -p 옵션으로 상위 디렉토리인 test까지 지우기 때문에 삭제가 가능하다.

 

  • -v 옵션 사용
[haechan@haechan ~/diroec]$ ll test3
total 0
drwxrwxr-x. 3 haechan haechan 18 Dec 24 17:28 test3

haechan@haechan ~/diroec]$ rmdir -pv test3/test/
rmdir: removing directory, ‘test3/test/’
rmdir: removing directory, ‘test3’

[haechan@haechan ~/diroec]$ ll test3
ls: cannot access test3: No such file or directory

 

rm 명령어 사용

-r 디렉토리를 삭제할 때 지정하는 옵션, 상위 디렉토리까지 삭제
-f 대상이 있다면 삭제할 것인지 물어보지 않고 강제로 삭제
-d 디렉토리가 빈 디렉토리일 경우 삭제

 

  • -rf 옵션 사용
haechan@haechan ~/diroec]$ tree
.
├── test
│   ├── test1
│   │   └── test2
│   └── testfile

[haechan@haechan ~/diroec]$ rm -rf test

[haechan@haechan ~/diroec]$ ll test
ls: cannot access test: No such file or directory

 

  • -d 옵션 사용
[haechan@haechan ~/diroec]$ tree
.
├── test2
│   ├── test1
│   │   └── test2
│   └── testfile
└── test3

[haechan@haechan ~/diroec]$ rm -dv *
rm: cannot remove ‘test2’: Directory not empty
removed directory: ‘test3’

[haechan@haechan ~/diroec]$ ll
total 0
drwxrwxr-x. 3 haechan haechan 35 Dec 24 17:49 test2

빈 디렉토리인 test3만 제거되는 모습을 확인할 수 있다.