はじめに
シェルスクリプトは、Linux 環境におけるタスクを自動化するための強力なツールです。シェルプログラミングにおける基本的なスキルの 1 つは、変数(データを保持する一時的なストレージ場所)を扱うことです。このチュートリアルでは、シェルスクリプトで変数を生成し、その値を表示するプロセスを説明します。この実験(Lab)の終わりには、変数を宣言し、その値にアクセスし、実用的なシェルスクリプトに組み込む方法を理解できるようになります。
シェルスクリプトは、Linux 環境におけるタスクを自動化するための強力なツールです。シェルプログラミングにおける基本的なスキルの 1 つは、変数(データを保持する一時的なストレージ場所)を扱うことです。このチュートリアルでは、シェルスクリプトで変数を生成し、その値を表示するプロセスを説明します。この実験(Lab)の終わりには、変数を宣言し、その値にアクセスし、実用的なシェルスクリプトに組み込む方法を理解できるようになります。
変数を宣言し、使用する方法を示す簡単なシェルスクリプトを作成することから始めましょう。
シェル変数は、シェルスクリプトで値を保持できる名前付きのストレージ場所です。テキスト文字列、数値、ファイルパス、コマンドの出力などのデータを保存および取得できます。変数は、スクリプトをより柔軟で再利用可能にします。
シェルスクリプトファイルを作成しましょう。
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)に格納します。echoステートメントで変数を使用して、パーソナライズされた出力を生成します。$((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を使用したコマンドライン引数(スクリプトに渡された最初の引数)$#を使用したパラメータチェック(引数の数)このバックアップスクリプトは、シェル変数を使用して、ファイル管理タスクを自動化するための便利で柔軟なツールを作成する方法の実用的な例です。
この実験(Lab)では、シェルスクリプトで変数を使用するための基本的なスキルを学びました。
echo、printf、引用符を使用して変数の値を表示するさまざまな方法これらのスキルは、シェルスクリプトの強固な基盤を形成し、Linux 環境でさまざまなタスクを自動化するための、より動的で柔軟なスクリプトを作成できるようになります。シェルスクリプトの学習を続けるにつれて、これらの概念を基盤として、システム管理、ファイル管理、データ処理タスクのための、より複雑なスクリプトを開発できます。