소개
Shell 스크립팅은 Linux 환경에서 작업을 자동화하는 강력한 도구입니다. 쉘 프로그래밍의 기본적인 기술 중 하나는 변수 (variables) - 데이터를 저장하는 임시 저장 위치 - 를 다루는 것입니다. 이 튜토리얼은 쉘 스크립트에서 변수를 생성하고 값을 출력하는 과정을 안내합니다. 이 랩을 마치면 변수를 선언하고, 값에 접근하며, 실용적인 쉘 스크립트에 이를 통합하는 방법을 이해하게 될 것입니다.
Shell 스크립팅은 Linux 환경에서 작업을 자동화하는 강력한 도구입니다. 쉘 프로그래밍의 기본적인 기술 중 하나는 변수 (variables) - 데이터를 저장하는 임시 저장 위치 - 를 다루는 것입니다. 이 튜토리얼은 쉘 스크립트에서 변수를 생성하고 값을 출력하는 과정을 안내합니다. 이 랩을 마치면 변수를 선언하고, 값에 접근하며, 실용적인 쉘 스크립트에 이를 통합하는 방법을 이해하게 될 것입니다.
변수를 선언하고 사용하는 방법을 보여주는 간단한 쉘 스크립트를 생성하여 시작해 보겠습니다.
쉘 변수는 쉘 스크립트에서 값을 저장할 수 있는 명명된 저장 위치입니다. 텍스트 문자열, 숫자, 파일 경로 및 명령 출력과 같은 데이터를 저장하고 검색할 수 있습니다. 변수는 스크립트를 더 유연하고 재사용 가능하게 만듭니다.
쉘 스크립트 파일을 만들어 보겠습니다.
cd ~/project
myscript.sh라는 새 파일을 생성합니다.
myscript.sh로 지정합니다.#!/bin/bash
## This is my first shell script with variables
## Declaring a variable
name="LabEx User"
## Printing the variable
echo "Hello, $name!"
## Printing the current date using a variable
current_date=$(date)
echo "Today is: $current_date"
Ctrl+S 를 누르거나 File > Save 를 클릭하여 파일을 저장합니다.
다음 명령을 사용하여 스크립트를 실행 가능하게 만듭니다.
chmod +x myscript.sh
스크립트를 실행합니다.
./myscript.sh
다음과 유사한 출력을 볼 수 있습니다.
Hello, LabEx User!
Today is: Thu Jul 13 10:30:45 UTC 2023
스크립트에서 일어난 일을 자세히 살펴보겠습니다.
#!/bin/bash (shebang 이라고 함) 은 시스템에 Bash 쉘을 사용하여 스크립트를 실행하도록 지시합니다.name이라는 변수를 생성하고 name="LabEx User"를 사용하여 "LabEx User" 값을 할당했습니다.echo "Hello, $name!"을 사용하여 변수의 값을 출력했습니다. 변수 이름 앞에 있는 $ 기호는 쉘에게 변수의 값을 대체하도록 지시합니다.current_date라는 다른 변수를 생성하고 $(date)를 사용하여 date 명령의 출력을 할당했습니다.current_date 변수의 값을 출력했습니다.쉘 스크립트에서 변수를 생성할 때 다음 명명 규칙을 따르십시오.
자신만의 변수를 포함하도록 스크립트를 수정하고 다시 실행하여 결과를 확인하십시오.
이제 변수를 생성하는 기본 사항을 이해했으므로 쉘 스크립트에서 변수 값을 출력하는 다양한 방법을 살펴보겠습니다.
변수를 출력하는 가장 일반적인 방법은 echo 명령과 함께 이중 인용 부호를 사용하는 것입니다. 이중 인용 부호는 쉘이 변수 이름을 해석하고 해당 값을 대체하도록 허용합니다.
print_variables.sh라는 새 파일을 생성합니다.
print_variables.sh로 지정합니다.#!/bin/bash
## Declaring variables
name="LabEx"
version=1.0
is_active=true
## Printing variables with double quotes
echo "Application name: $name"
echo "Version: $version"
echo "Active status: $is_active"
## Printing multiple variables in one statement
echo "The $name application version $version is $is_active"
chmod +x print_variables.sh
./print_variables.sh
다음과 유사한 출력을 볼 수 있습니다.
Application name: LabEx
Version: 1.0
Active status: true
The LabEx application version 1.0 is true
때로는 변수 이름이 시작하고 끝나는 위치에 대해 더 정확해야 할 필요가 있습니다. 중괄호는 변수 이름을 명확하게 구분하여 이를 돕습니다.
print_variables.sh 스크립트에 다음 줄을 추가합니다.
## Using curly braces to clearly define variable boundaries
app="${name}App"
echo "Application full name: $app"
## This avoids confusion when you want to append text directly to a variable's value
echo "Application name with text: ${name}Text"
스크립트를 저장하고 다시 실행합니다.
./print_variables.sh
추가 출력은 다음과 같이 표시됩니다.
Application full name: LabExApp
Application name with text: LabExText
이중 인용 부호와 달리 작은 따옴표는 변수 대체를 방지하고 리터럴 텍스트를 출력합니다.
이 줄을 스크립트에 추가합니다.
## Using single quotes (no variable substitution)
echo 'With single quotes: $name is not replaced'
## Mixing quote types for complex output
echo "This is the variable value: '$name'"
스크립트를 저장하고 다시 실행합니다. 다음을 볼 수 있습니다.
With single quotes: $name is not replaced
This is the variable value: 'LabEx'
printf 명령은 출력 형식에 대한 더 많은 제어를 제공합니다.
## Using printf for formatted output
printf "Name: %s\nVersion: %.1f\n" "$name" "$version"
## Formatting numbers with printf
number=42.5678
printf "Formatted number: %.2f\n" $number
스크립트를 저장하고 다시 실행합니다. 추가 출력은 다음과 같이 표시됩니다.
Name: LabEx
Version: 1.0
Formatted number: 42.57
다양한 출력 방법을 실험하여 필요에 가장 적합한 방법을 확인하십시오.
이제 사용자 입력을 받아 변수에 저장하고 결과를 표시하는 더 실용적인 쉘 스크립트를 만들어 보겠습니다.
read 명령을 사용하면 스크립트가 사용자로부터 입력을 받을 수 있습니다. 간단한 인사말 스크립트를 만들어 보겠습니다.
greeting.sh라는 새 파일을 생성합니다.
greeting.sh로 지정합니다.#!/bin/bash
## Simple greeting script that takes user input
## Prompt the user for their name
echo "What is your name?"
read username
## Prompt for age
echo "How old are you?"
read age
## Display a greeting with the provided information
echo "Hello, $username! You are $age years old."
## Calculate birth year (approximately)
current_year=$(date +%Y)
birth_year=$((current_year - age))
echo "You were born around the year $birth_year."
## Adding a personalized message based on age
if [ $age -lt 18 ]; then
echo "You are a minor."
elif [ $age -ge 18 ] && [ $age -lt 65 ]; then
echo "You are an adult."
else
echo "You are a senior."
fi
파일을 저장합니다 (Ctrl+S 또는 File > Save).
실행 가능하게 만듭니다.
chmod +x greeting.sh
스크립트를 실행합니다.
./greeting.sh
메시지가 표시되면 이름과 나이를 입력합니다. 입력에 따라 개인화된 출력을 볼 수 있습니다.
이 스크립트의 주요 부분을 분석해 보겠습니다.
read 명령은 사용자 입력을 변수 (username 및 age) 에 저장합니다.$((expression)) 구문을 사용하여 산술 연산을 수행하여 출생 연도를 계산합니다.if, elif, else) 을 사용하여 나이 값에 따라 다른 메시지를 제공합니다.date 명령을 사용합니다.스크립트를 향상시켜 더 대화형으로 만들고 유용하게 만들어 보겠습니다. greeting.sh 파일에 다음을 추가합니다.
## Ask if the user wants to see the current system information
echo "Would you like to see some system information? (yes/no)"
read response
## Convert the response to lowercase for easier comparison
response_lower=$(echo "$response" | tr '[:upper:]' '[:lower:]')
if [ "$response_lower" = "yes" ] || [ "$response_lower" = "y" ]; then
echo "System information for user $username:"
echo "-------------------------------------"
echo "Hostname: $(hostname)"
echo "Kernel version: $(uname -r)"
echo "System uptime: $(uptime -p)"
echo "CPU information: $(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | sed 's/^[ \t]*//')"
echo "Memory available: $(free -h | grep Mem | awk '{print $7}')"
echo "-------------------------------------"
else
echo "No problem, $username. Have a great day!"
fi
파일을 저장하고 다시 실행합니다.
./greeting.sh
프롬프트를 따르고 시스템 정보를 보려면 "yes"를 입력합니다. 시스템에 대한 자세한 정보를 볼 수 있습니다.
이 스크립트는 다음을 수행하는 방법을 보여줍니다.
스크립트를 수정하여 더 많은 대화형 기능이나 다른 유형의 시스템 정보를 추가해 보십시오.
쉘 변수에 대한 지식을 적용하여 파일 작업을 수행하는 유용한 스크립트를 만들어 보겠습니다. 이 스크립트는 변수가 파일 관리 작업을 자동화하는 데 어떻게 도움이 되는지 보여줍니다.
지정된 디렉토리의 파일 백업을 만드는 스크립트를 만들어 보겠습니다.
먼저, 작업할 테스트 디렉토리와 몇 가지 샘플 파일을 만들어 보겠습니다.
mkdir -p ~/project/test_files
echo "This is file 1" > ~/project/test_files/file1.txt
echo "This is file 2" > ~/project/test_files/file2.txt
echo "This is file 3" > ~/project/test_files/file3.txt
이제 backup.sh라는 새 파일을 생성합니다.
backup.sh로 지정합니다.#!/bin/bash
## A script to backup files from a source directory to a backup directory
## Define variables for directories
source_dir="$HOME/project/test_files"
backup_dir="$HOME/project/backup"
date_stamp=$(date +"%Y%m%d_%H%M%S")
backup_name="backup_$date_stamp"
## Print the script's purpose
echo "File Backup Script"
echo "==================="
echo "Source directory: $source_dir"
echo "Backup directory: $backup_dir/$backup_name"
## Create the backup directory if it doesn't exist
if [ ! -d "$backup_dir" ]; then
echo "Creating backup directory: $backup_dir"
mkdir -p "$backup_dir"
fi
## Create a timestamped backup directory
mkdir -p "$backup_dir/$backup_name"
## Check if source directory exists
if [ ! -d "$source_dir" ]; then
echo "Error: Source directory $source_dir does not exist!"
exit 1
fi
## Count the number of files in the source directory
file_count=$(ls -1 "$source_dir" | wc -l)
echo "Found $file_count files in the source directory."
## Copy the files to the backup directory
echo "Copying files to backup location..."
cp -r "$source_dir"/* "$backup_dir/$backup_name"
## Verify the copy operation
copied_count=$(ls -1 "$backup_dir/$backup_name" | wc -l)
echo "Copied $copied_count files to the backup directory."
## Check if all files were copied successfully
if [ "$file_count" -eq "$copied_count" ]; then
echo "Backup completed successfully!"
else
echo "Warning: Not all files were copied. Please check for errors."
fi
## List the contents of the backup directory
echo "Contents of the backup directory:"
ls -la "$backup_dir/$backup_name"
## Display the total size of the backup
backup_size=$(du -sh "$backup_dir/$backup_name" | cut -f1)
echo "Total backup size: $backup_size"
chmod +x backup.sh
./backup.sh
다음과 같은 백업 프로세스를 보여주는 출력을 볼 수 있습니다.
이 백업 스크립트는 몇 가지 중요한 개념을 보여줍니다.
$(command) 구문을 사용하여 명령 출력을 변수에 캡처합니다.if 문을 사용합니다.$HOME을 사용합니다.mkdir, cp 및 ls와 같은 쉘 명령을 사용합니다.exit 1을 사용합니다.사용자 지정 소스 디렉토리를 수락하도록 스크립트를 수정해 보겠습니다.
backup.sh를 엽니다.#!/bin/bash
## A script to backup files from a source directory to a backup directory
## Check if a source directory was provided
if [ $## -eq 0 ]; then
## No argument provided, use default directory
source_dir="$HOME/project/test_files"
echo "No source directory specified, using default: $source_dir"
else
## Use the provided directory
source_dir="$1"
echo "Using specified source directory: $source_dir"
fi
## Define variables for directories
backup_dir="$HOME/project/backup"
date_stamp=$(date +"%Y%m%d_%H%M%S")
backup_name="backup_$date_stamp"
## Print the script's purpose
echo "File Backup Script"
echo "==================="
echo "Source directory: $source_dir"
echo "Backup directory: $backup_dir/$backup_name"
## Create the backup directory if it doesn't exist
if [ ! -d "$backup_dir" ]; then
echo "Creating backup directory: $backup_dir"
mkdir -p "$backup_dir"
fi
## Create a timestamped backup directory
mkdir -p "$backup_dir/$backup_name"
## Check if source directory exists
if [ ! -d "$source_dir" ]; then
echo "Error: Source directory $source_dir does not exist!"
exit 1
fi
## Count the number of files in the source directory
file_count=$(ls -1 "$source_dir" | wc -l)
echo "Found $file_count files in the source directory."
## Copy the files to the backup directory
echo "Copying files to backup location..."
cp -r "$source_dir"/* "$backup_dir/$backup_name"
## Verify the copy operation
copied_count=$(ls -1 "$backup_dir/$backup_name" | wc -l)
echo "Copied $copied_count files to the backup directory."
## Check if all files were copied successfully
if [ "$file_count" -eq "$copied_count" ]; then
echo "Backup completed successfully!"
else
echo "Warning: Not all files were copied. Please check for errors."
fi
## List the contents of the backup directory
echo "Contents of the backup directory:"
ls -la "$backup_dir/$backup_name"
## Display the total size of the backup
backup_size=$(du -sh "$backup_dir/$backup_name" | cut -f1)
echo "Total backup size: $backup_size"
./backup.sh ~/project
향상된 스크립트는 이제 다음을 보여줍니다.
$1을 사용한 명령줄 인수 (스크립트에 전달된 첫 번째 인수)$#을 사용한 매개변수 확인 (인수 수)이 백업 스크립트는 쉘 변수를 사용하여 파일 관리 작업을 자동화하기 위한 유용하고 유연한 도구를 만드는 실용적인 예입니다.
이 랩에서는 쉘 스크립트에서 변수를 사용하는 데 필요한 필수 기술을 배웠습니다.
이러한 기술은 쉘 스크립팅의 견고한 기반을 형성하며 Linux 환경에서 다양한 작업을 자동화하기 위한 보다 동적이고 유연한 스크립트를 생성할 수 있게 해줍니다. 쉘 스크립팅 여정을 계속 진행하면서 이러한 개념을 기반으로 시스템 관리, 파일 관리 및 데이터 처리 작업을 위한 보다 복잡한 스크립트를 개발할 수 있습니다.