본문 바로가기

Language&Configuration/[Liunx]

[Linux] chmod 명령어 사용법 - 파일 권한 변경하기

1. 개 요

chmod 명령어는 리눅스의 파일이나 디렉토리의 권한을 변경하는 명령어입니다.

 

2. 사용법

리눅스에서 사용되는 명령어는 모두 대소문자를 구분합니다.

Usage:chmod [OPTION]... MODE[,MODE]... FILE...
or:chmod [OPTION]... OCTAL-MODE FILE...
or:chmod [OPTION]... --reference=RFILE FILE...
Change the mode of each FILE to MODE.
With --reference, change the mode of each FILE to that of RFILE.
-c, --changes like verbose but report only when a change is made
-f, --silent, --quiet suppress most error messages
-v, --verbose output a diagnostic for every file processed
--no-preserve-root do not treat '/' specially (the default)
--preserve-root fail to operate recursively on '/'
--reference=RFILE use RFILE's mode instead of MODE values
-R, --recursive change files and directories recursively
--help display this help and exit
--version output version information and exit

Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'.

기본 사용법은 아래와 같이 변경하고자 하는 권한과 파일명을 명시하여 실행하면 됩니다.

chmod 755 test.txt

 

3. 리눅스 파일 권한

리눅스 파일은 user, group, others 별로 read, write, execute 권한을 부여할 수 있습니다.

ls 명령으로 현재 파일에 부여되어 있는 권한을 확인할 수 있습니다.

[root@test] ls -l
total 0
-rw-r--r-- 1 root root 0 Jun  4 08:45 test.txt

-rw-r--r-- 에서 맨앞의 - 는 file 인지 directory인지 구분하는 symbol 입니다.

[root@test]# ls -l
total 44
-rwxr-xr-x 1 root root 8576 May 10 08:38 a.out
-rw-r--r-- 1 root root  214 May 10 08:38 arr1.c
-rw-r--r-- 1 root root  425 May 10 07:30 arr.c
drwxr-xr-x 2 root root 4096 Jun  4 08:45 ch
drwxr-xr-x 2 root root 4096 May  3 14:27 john
-rw-r--r-- 1 root root    0 May  8 14:40 mv_test.dat
-rw-r--r-- 1 root root    0 May  9 06:06 new_file
-rw-r--r-- 1 root root    5 May  9 06:09 new.txt
drwxr-xr-x 2 root root 4096 May  3 14:27 test
-rw-r--r-- 1 root root   33 May 14 09:00 test1.txt
-rw-r--r-- 1 root root   33 May  8 14:56 test2.txt

이렇게 directory인 경우에는 d 라는 symbol로 표시됩니다.

rw-r--r-- 로 표시되는 부분이 부여된 권한을 나타내는데 3개씩 끊어서 보면

  • 앞에 3개가 user소유자(owner)의 권한
  • 중간에 3개는 group 에 대한 권한
  • 마지막 3개가 others 에 대한 권한

이 권한을 8진수로 표현하면 rwx 권한을 다 갖는 경우 7이 됩니다.
각 권한을 숫자값으로 표현하면 r = 4, w = 2, x = 1 이기 때문에
r + w + x = 7

파일에 user와 group 에 대해서만 read 권한을 부여하려면 440 으로 적용하면 됩니다.
+, - 기호를 사용해서 특정 권한을 더하거나 뺄 수도 있습니다.

4. 예제

ex) text.txt 파일에 대해서 user의 모든권한을 부여하고 group과 others는 모든 권한을 제외

chmod 700 test.txt

ex) text.txt 파일에 대해서 실행 권한 추가 부여

chmod +x test.txt

ex) text.txt 파일에 대해서 group에 write 권한 부여

chmod g+w test.txt

ex) text.txt 파일에 대해서 others의 모든 권한 박탈

chmod o-rwx test.txt