Bash Shell - File 테스트 연산자

Bash shell의 File 테스트 연산자를 소개합니다.

다음과 같은 연산자를 이용하여 파일이 존재하는지, 파일이 디렉토리인지 등을 확인할 수 있습니다.

File test operation Description
-e file exists
-a file exists (deprecated)
-f file is a regular file (not a directory or device file)
-s file is not zero size
-d file is a directory
-b file is a block device
-c file is a character device
-p file is a pipe
-h file is a symbolic link
-L file is a symbolic link
-S file is a socket
-t file (descriptor) is associated with a terminal device
-r file has read permission (for the user running the test)
-w file has write permission (for the user running the test)
-x file has execute permission (for the user running the test)
-g set-group-id (sgid) flag set on file or directory
-u set-user-id (suid) flag set on file
-k sticky bit set
-O you are owner of file
-G group-id of file same as yours
-N file modified since it was last read
f1 -nt f2 file f1 is newer than f2
f1 -ot f2 file f1 is older than f2
f1 -ef f2 files f1 and f2 are hard links to the same file
! "not" -- reverses the sense of the tests above (returns true if condition absent)

Example 1

파일이 존재하는지 확인하는 예제입니다. 파일 경로는 절대경로나 상대경로를 입력할 수 있습니다.

#!/bin/bash

SAMPLE_FILE="./example.sh"

if [ -e "$SAMPLE_FILE" ]
then
    echo "Sample file exists"
fi

Output:

$ bash example.sh
Sample file exists

Example 2

디렉토리가 아닌, 단순한 파일이 존재하는지 확인하는 것이라면 -f를 사용하여 체크할 수도 있습니다.

#!/bin/bash

SAMPLE_FILE="./example.sh"

if [ -f "$SAMPLE_FILE" ]
then
    echo "Sample file exists"
fi

Output:

$ bash example.sh
Sample file exists

Example 3

파일이 존재하지 않는지 확인할 때는 연산자 앞에 not(!)을 추가해주시면 됩니다.

#!/bin/bash

SAMPLE_FILE="./example1.sh"

if [ ! -f "$SAMPLE_FILE" ]
then
    echo "Sample file doesn't exists"
fi

Output:

$ bash example.sh
Sample file doesn't exists
Loading script...

Related Posts

codechachaCopyright ©2019 codechacha