리눅스 논리 연산

LinuxBeginner
지금 연습하기

소개

Linux 논리 연산 랩에 오신 것을 환영합니다. 이 랩에서는 Linux 에서 논리 연산에 대해 배우게 됩니다. 이는 명령 실행 흐름을 제어하고 스크립트에서 의사 결정을 내리는 데 필수적인 도구입니다.

논리 연산을 사용하면 명령과 조건을 결합하여 다양한 상황에 대응할 수 있는 더욱 정교한 스크립트를 만들 수 있습니다. 이 랩을 마치면 Linux 에서 논리 연산자를 사용하여 명령 실행을 제어하고 파일 속성을 확인하는 방법을 이해하게 될 것입니다.

이것은 가이드 실험입니다. 학습과 실습을 돕기 위한 단계별 지침을 제공합니다.각 단계를 완료하고 실무 경험을 쌓기 위해 지침을 주의 깊게 따르세요. 과거 데이터에 따르면, 이것은 초급 레벨의 실험이며 완료율은 94%입니다.학습자들로부터 100%의 긍정적인 리뷰율을 받았습니다.

Linux 기본 논리 연산 이해

Linux 셸은 논리 연산자를 사용하여 명령과 조건을 결합하는 여러 가지 방법을 제공합니다. 이 단계에서는 가장 일반적으로 사용되는 논리 연산자인 && (AND) 와 || (OR) 에 대해 배우게 됩니다.

먼저, 프로젝트 디렉토리로 이동해 보겠습니다.

cd ~/project

이 랩 전체에서 사용할 몇 가지 테스트 파일을 만들어 보겠습니다.

touch treasure_map.txt shield.txt kings_gauntlet.txt

이제 기본적인 논리 연산을 시연하기 위한 스크립트를 만들어 보겠습니다. nano 텍스트 편집기를 사용하여 logic_basics.sh라는 파일을 만듭니다.

nano logic_basics.sh

이 스크립트에서는 논리 연산자를 사용하여 두 파일이 존재하는지 확인합니다. 다음 코드를 편집기에 입력하거나 붙여넣으세요.

#!/bin/bash

## This script demonstrates logical AND (&&) and OR (||) operators
## It checks if two specific files exist in the current directory

if [[ -f "treasure_map.txt" ]] && [[ -f "shield.txt" ]]; then
  echo "Both files exist. Proceed with the mission."
else
  echo "One or both files are missing. Abort the mission!"
fi

&& 연산자는 "AND"를 의미합니다. 전체 조건이 참이 되려면 두 조건 모두 참이어야 합니다.
-f 테스트는 파일이 존재하고 일반 파일인지 (디렉토리 또는 기타 특수 파일이 아닌지) 확인합니다.

nano 에서 파일을 저장하려면 Ctrl+X를 누른 다음 Y를 눌러 저장을 확인하고 Enter를 눌러 파일 이름을 확인합니다.

이제 스크립트를 실행 가능하게 만들고 실행해 보겠습니다.

chmod +x logic_basics.sh
./logic_basics.sh

다음 출력을 볼 수 있습니다.

Both files exist. Proceed with the mission.

논리 연산자를 더 잘 이해하기 위해 다른 예를 시도해 보겠습니다. logical_or.sh라는 새 스크립트를 만듭니다.

nano logical_or.sh

다음 내용을 추가합니다.

#!/bin/bash

## This script demonstrates the logical OR (||) operator
## It checks if at least one of two files exists

if [[ -f "treasure_map.txt" ]] || [[ -f "nonexistent_file.txt" ]]; then
  echo "At least one file exists."
else
  echo "Neither file exists."
fi

|| 연산자는 "OR"를 의미합니다. 두 조건 중 하나라도 참이면 전체 조건이 참입니다.

파일을 저장하고 (Ctrl+X, Y, Enter), 실행 가능하게 만들고, 실행합니다.

chmod +x logical_or.sh
./logical_or.sh

출력:

At least one file exists.

이것은 "nonexistent_file.txt"가 존재하지 않더라도 "treasure_map.txt"가 존재하기 때문에 조건이 여전히 참임을 보여줍니다.

파일 권한을 이용한 논리 연산

Linux 에서 파일 권한은 파일을 읽고, 쓰고, 실행할 수 있는 사용자를 제어합니다. 이 단계에서는 논리 연산을 사용하여 파일 권한을 확인하는 방법을 배우게 됩니다.

먼저, permission_check.sh라는 스크립트를 만들어 보겠습니다.

nano permission_check.sh

다음 내용을 스크립트에 추가합니다.

#!/bin/bash

## This script checks read and write permissions on a file
## using logical operators

filename="kings_gauntlet.txt"

if [[ -r "$filename" ]] && [[ -w "$filename" ]]; then
  echo "You have read and write permissions on $filename."
elif [[ -r "$filename" ]] || [[ -w "$filename" ]]; then
  echo "You have limited permissions on $filename."
else
  echo "You do not have permissions on $filename."
fi

이 스크립트에서:

  • -r은 현재 사용자가 파일을 읽을 수 있는지 테스트합니다.
  • -w는 현재 사용자가 파일을 쓸 수 있는지 테스트합니다.
  • && 연산자는 두 조건 모두 참이어야 합니다.
  • || 연산자는 최소한 하나의 조건이 참이어야 합니다.

파일을 저장하고 (Ctrl+X, Y, Enter) 실행 가능하게 만듭니다.

chmod +x permission_check.sh

이제 테스트 파일의 권한을 수정하고 스크립트 출력에 어떤 영향을 미치는지 살펴보겠습니다.

먼저, 읽기 및 쓰기를 모두 허용하도록 권한을 설정해 보겠습니다.

chmod 600 kings_gauntlet.txt
./permission_check.sh

출력:

You have read and write permissions on kings_gauntlet.txt.

이제 권한을 읽기 전용으로 변경해 보겠습니다.

chmod 400 kings_gauntlet.txt
./permission_check.sh

출력:

You have limited permissions on kings_gauntlet.txt.

마지막으로, 모든 권한을 제거해 보겠습니다.

chmod 000 kings_gauntlet.txt
./permission_check.sh

출력:

You do not have permissions on kings_gauntlet.txt.

파일에 적절한 권한을 복원하는 것을 잊지 마세요.

chmod 600 kings_gauntlet.txt

논리 연산자를 사용한 명령어 체이닝

Linux 의 논리 연산자는 스크립트의 조건문뿐만 아니라 명령줄에서 명령을 함께 연결하는 데에도 직접 사용할 수 있습니다. 이 단계에서는 명령 체이닝을 위해 논리 연산자를 사용하는 방법을 배우게 됩니다.

&& 연산자를 사용하면 첫 번째 명령이 성공하면 (0 의 종료 상태를 반환) 두 번째 명령을 실행할 수 있습니다. 이는 각 단계가 이전 단계의 성공에 의존하는 일련의 명령을 실행하는 데 유용합니다.

간단한 예제를 시도해 보겠습니다.

mkdir -p test_dir && echo "Directory created successfully"

mkdir -p 명령은 디렉토리를 생성하고 (필요한 경우 상위 디렉토리도 생성) -p 옵션은 디렉토리가 이미 존재하는 경우 오류를 방지합니다. echo 명령은 mkdir 명령이 성공한 경우에만 실행됩니다.

출력:

Directory created successfully

이제 첫 번째 명령이 실패한 경우에만 두 번째 명령을 실행하는 || 연산자를 시도해 보겠습니다.

ls nonexistent_file.txt || echo "File not found"

"nonexistent_file.txt"가 존재하지 않으므로 ls 명령이 실패하고 echo 명령이 실행됩니다.

출력:

ls: cannot access 'nonexistent_file.txt': No such file or directory
File not found

이러한 연산자를 사용하여 여러 명령을 결합할 수도 있습니다. command_chain.sh라는 스크립트를 만듭니다.

nano command_chain.sh

다음 내용을 추가합니다.

#!/bin/bash

## This script demonstrates chaining commands with logical operators

echo "Starting command chain..."

## Create a directory and enter it only if creation succeeds
mkdir -p logic_test && cd logic_test && echo "Changed to new directory"

## Create a file and write to it only if creation succeeds
touch test_file.txt && echo "This is a test" > test_file.txt && echo "Created and wrote to file"

## Try to read a nonexistent file, or display an error message
cat nonexistent.txt || echo "Failed to read file"

## Return to the original directory
cd .. && echo "Returned to original directory"

echo "Command chain completed"

파일을 저장하고 (Ctrl+X, Y, Enter) 실행 가능하게 만들고 실행합니다.

chmod +x command_chain.sh
./command_chain.sh

출력:

Starting command chain...
Changed to new directory
Created and wrote to file
cat: nonexistent.txt: No such file or directory
Failed to read file
Returned to original directory
Command chain completed

이 스크립트는 논리 연산자가 이전 명령의 성공 또는 실패에 따라 명령 실행 흐름을 제어하는 ​​방법을 보여줍니다.

고급 파일 테스트 연산자

Linux 는 논리 연산자와 결합할 수 있는 다양한 파일 테스트 연산자를 제공합니다. 이 단계에서는 가장 유용한 파일 테스트 연산자 중 일부에 대해 배우게 됩니다.

이러한 연산자를 보여주는 스크립트를 만들어 보겠습니다.

nano file_tests.sh

다음 내용을 추가합니다.

#!/bin/bash

## This script demonstrates various file testing operators in Linux

## Check if a file exists (as a file, directory, or other type)
file_to_check="treasure_map.txt"
directory_to_check="test_dir"

echo "--- Basic File Tests ---"
## -e checks if the file exists (any type)
if [[ -e "$file_to_check" ]]; then
  echo "$file_to_check exists"
else
  echo "$file_to_check does not exist"
fi

## -f checks if it's a regular file (not a directory or device)
if [[ -f "$file_to_check" ]]; then
  echo "$file_to_check is a regular file"
fi

## -d checks if it's a directory
if [[ -d "$directory_to_check" ]]; then
  echo "$directory_to_check is a directory"
else
  echo "$directory_to_check is not a directory"
fi

echo "--- File Size Tests ---"
## -s checks if file is not empty (has a size greater than zero)
if [[ -s "$file_to_check" ]]; then
  echo "$file_to_check is not empty"
else
  echo "$file_to_check is empty"
fi

echo "--- Permission Tests ---"
## -r, -w, -x check read, write, and execute permissions
if [[ -r "$file_to_check" ]]; then
  echo "$file_to_check is readable"
fi

if [[ -w "$file_to_check" ]]; then
  echo "$file_to_check is writable"
fi

if [[ -x "$file_to_check" ]]; then
  echo "$file_to_check is executable"
else
  echo "$file_to_check is not executable"
fi

echo "--- Combining Tests with Logical Operators ---"
## Combining tests with AND (&&)
if [[ -f "$file_to_check" ]] && [[ -r "$file_to_check" ]]; then
  echo "$file_to_check is a readable file"
fi

## Combining tests with OR (||)
if [[ -f "$file_to_check" ]] || [[ -d "$file_to_check" ]]; then
  echo "$file_to_check is either a file or a directory"
fi

파일을 저장하고 (Ctrl+X, Y, Enter) 실행 가능하게 만들고 실행합니다.

chmod +x file_tests.sh
./file_tests.sh

출력은 기존 파일 및 디렉토리에 대한 다양한 파일 테스트의 결과를 보여줍니다.

테스트를 더 흥미롭게 만들기 위해 treasure_map.txt 파일에 일부 내용을 추가하고 테스트할 디렉토리를 만들어 보겠습니다.

echo "This is a treasure map!" > treasure_map.txt
mkdir -p test_dir

이제 스크립트를 다시 실행합니다.

./file_tests.sh

이제 파일에 내용이 있고 디렉토리가 존재하므로 다른 출력을 볼 수 있습니다.

이 스크립트는 다양한 파일 테스트 연산자를 사용하고 이를 논리 연산자와 결합하여 정교한 파일 검사를 만드는 방법을 보여줍니다.

요약

이 랩에서는 Linux 의 논리 연산과 명령 실행 흐름 및 스크립트 동작을 제어하는 ​​방법에 대해 배웠습니다. 다음은 학습 내용 요약입니다.

  1. 기본 논리 연산자 && (AND) 및 || (OR) 와 이를 조건문에서 사용하는 방법에 대해 배웠습니다.

  2. 파일 존재 여부 및 권한을 확인하기 위해 -f, -r, -w, -x와 같은 파일 테스트 연산자를 사용했습니다.

  3. 이전 명령의 성공 또는 실패에 따라 달라지는 일련의 작업을 생성하기 위해 논리 연산자를 사용하여 명령을 함께 체이닝하는 연습을 했습니다.

  4. 다양한 파일 테스트 연산자를 살펴보고 이를 논리 연산자와 결합하여 더 복잡한 조건을 만드는 방법을 배웠습니다.

이러한 논리 연산은 Linux 스크립팅 및 명령줄 사용의 기본적인 도구입니다. 이를 통해 조건 및 이전 명령 결과에 따라 다양한 상황을 처리할 수 있는 더 정교한 스크립트를 만들 수 있습니다.

논리 연산을 마스터함으로써 Linux 사용자 또는 관리자로서의 여정에서 도움이 될 Linux 시스템 관리, 자동화 및 스크립팅에 필수적인 기술을 습득했습니다.