はじめに
このチュートリアルでは、人気のシェルスクリプト言語である Bash で変数を割り当てたり、再割り当てしたりするプロセスを説明します。変数は、Bash スクリプトの基本的な構成要素であり、データを保存し操作するために使用されます。この実践的な実験(Lab)では、変数を宣言し、値を割り当て、コマンドやスクリプトで使用する方法を学びます。このチュートリアルを終える頃には、Bash で変数を効果的に扱う方法をしっかりと理解し、より強力で柔軟なスクリプトを作成できるようになるでしょう。
このチュートリアルでは、人気のシェルスクリプト言語である Bash で変数を割り当てたり、再割り当てしたりするプロセスを説明します。変数は、Bash スクリプトの基本的な構成要素であり、データを保存し操作するために使用されます。この実践的な実験(Lab)では、変数を宣言し、値を割り当て、コマンドやスクリプトで使用する方法を学びます。このチュートリアルを終える頃には、Bash で変数を効果的に扱う方法をしっかりと理解し、より強力で柔軟なスクリプトを作成できるようになるでしょう。
Bash では、変数はスクリプト内で後からアクセスして変更できるデータを保存できます。まず、簡単な変数を作成し、それに値を割り当てることから始めましょう。
LabEx 環境で新しいターミナルを開きます。/home/labex/project ディレクトリにいるはずです。
Bash で変数に値を割り当てるには、次の構文を使用します。
variable_name=value
等号の周りにスペースを入れてはいけないことに注意してください。
最初の変数を作成しましょう。
name="John"
$) を前に付けた変数名とともに echo コマンドを使用します。echo $name
次のような出力が表示されるはずです。
John
echo "My name is $name"
出力:
My name is John
=) をもう一度使用するだけです。name="Alice"
echo "My name is $name"
出力:
My name is Alice
Bash で変数を作成する際は、次の命名規則に従ってください。
変数を使った練習をするために、ファイルを作成しましょう。WebIDE で、プロジェクトディレクトリに variables.sh という名前の新しいファイルを作成します。
variables.sh とします。#!/bin/bash
## Assigning variables
first_name="John"
last_name="Doe"
age=25
## Displaying variables
echo "First name: $first_name"
echo "Last name: $last_name"
echo "Age: $age"
## Reassigning variables
first_name="Jane"
echo "Updated first name: $first_name"
Ctrl+S を押すか、File → Save をクリックしてファイルを保存します。
ターミナルで次のコマンドを実行して、スクリプトを実行可能にします。
chmod +x variables.sh
./variables.sh
次のような出力が表示されるはずです。
First name: John
Last name: Doe
Age: 25
Updated first name: Jane
これは、変数の作成、値の割り当て、および新しい値の再割り当ての方法を示しています。
このステップでは、文字列操作や算術計算など、Bash で変数の値を操作するさまざまな方法を探ります。
Bash は、変数に格納された文字列値を操作するためのいくつかの方法を提供します。
string_operations.sh という名前の新しいファイルを作成します。#!/bin/bash
## String concatenation
greeting="Hello"
name="World"
message="$greeting $name"
echo $message
## String length
text="Welcome to Bash scripting"
length=${#text}
echo "The length of '$text' is $length characters"
## Extracting substrings
substring=${text:0:7}
echo "Substring: $substring"
## Converting to uppercase and lowercase
uppercase=${text^^}
lowercase=${text,,}
echo "Uppercase: $uppercase"
echo "Lowercase: $lowercase"
chmod +x string_operations.sh
./string_operations.sh
次のような出力が表示されるはずです。
Hello World
The length of 'Welcome to Bash scripting' is 25 characters
Substring: Welcome
Uppercase: WELCOME TO BASH SCRIPTING
Lowercase: welcome to bash scripting
Bash では、変数を使用した算術演算も実行できます。
arithmetic_operations.sh という名前の新しいファイルを作成します。#!/bin/bash
## Assigning numeric values
x=5
y=3
## Basic arithmetic operations
sum=$((x + y))
difference=$((x - y))
product=$((x * y))
quotient=$((x / y))
remainder=$((x % y))
## Display results
echo "x = $x, y = $y"
echo "Sum: $x + $y = $sum"
echo "Difference: $x - $y = $difference"
echo "Product: $x * $y = $product"
echo "Quotient: $x / $y = $quotient"
echo "Remainder: $x % $y = $remainder"
## Increment and decrement
echo "Initial value of x: $x"
x=$((x + 1))
echo "After increment: $x"
x=$((x - 1))
echo "After decrement: $x"
## Compound assignment operators
x+=5
echo "After x+=5: $x"
x-=2
echo "After x-=2: $x"
chmod +x arithmetic_operations.sh
./arithmetic_operations.sh
次のような出力が表示されるはずです。
x = 5, y = 3
Sum: 5 + 3 = 8
Difference: 5 - 3 = 2
Product: 5 * 3 = 15
Quotient: 5 / 3 = 1
Remainder: 5 % 3 = 2
Initial value of x: 5
After increment: 6
After decrement: 5
After x+=5: 10
After x-=2: 8
変数には、ユーザーが提供した入力を格納することもできます。ユーザーに入力を求めるスクリプトを作成しましょう。
user_input.sh という名前のファイルを作成します。#!/bin/bash
## Prompt the user for their name
echo "What is your name?"
read user_name
## Prompt the user for their age
echo "How old are you?"
read user_age
## Display the information
echo "Hello, $user_name! You are $user_age years old."
## Calculate birth year (approximate)
current_year=$(date +%Y)
birth_year=$((current_year - user_age))
echo "You were likely born in $birth_year."
chmod +x user_input.sh
./user_input.sh
このステップでは、文字列操作、算術計算、ユーザー入力の読み取りなど、変数を使用したさまざまな操作を実行する方法を示しました。
このステップでは、Bash スクリプトとコマンドで変数を効果的に使用する方法を探ります。さまざまなシナリオでの変数の使用を示す実用的なスクリプトを作成します。
ショッピングカート内の商品の合計金額を計算するスクリプトを作成しましょう。
shopping_cart.sh という名前の新しいファイルを作成します。#!/bin/bash
## Initialize variables for items and their prices
item1="Laptop"
price1=999
item2="Headphones"
price2=149
item3="Mouse"
price3=25
## Calculate the total price
total=$((price1 + price2 + price3))
## Display the shopping cart
echo "Shopping Cart:"
echo "-------------"
echo "$item1: \$$price1"
echo "$item2: \$$price2"
echo "$item3: \$$price3"
echo "-------------"
echo "Total: \$$total"
## Apply a discount if the total is over $1000
discount_threshold=1000
discount_rate=10
if [ $total -gt $discount_threshold ]; then
discount_amount=$((total * discount_rate / 100))
discounted_total=$((total - discount_amount))
echo "Discount (${discount_rate}%): -\$$discount_amount"
echo "Final Total: \$$discounted_total"
fi
chmod +x shopping_cart.sh
./shopping_cart.sh
次のような出力が表示されるはずです。
Shopping Cart:
-------------
Laptop: $999
Headphones: $149
Mouse: $25
-------------
Total: $1173
Discount (10%): -$117
Final Total: $1056
コマンド置換を使用すると、コマンドの出力を取得して変数に格納できます。これを示すスクリプトを作成しましょう。
system_info.sh という名前の新しいファイルを作成します。#!/bin/bash
## Get current date and time
current_date=$(date +"%Y-%m-%d")
current_time=$(date +"%H:%M:%S")
## Get system information
hostname=$(hostname)
os_type=$(uname -s)
kernel_version=$(uname -r)
uptime_info=$(uptime -p)
memory_free=$(free -h | awk '/^Mem:/ {print $4}')
disk_free=$(df -h / | awk 'NR==2 {print $4}')
## Display the information
echo "System Information Report"
echo "========================="
echo "Date: $current_date"
echo "Time: $current_time"
echo "Hostname: $hostname"
echo "OS Type: $os_type"
echo "Kernel Version: $kernel_version"
echo "Uptime: $uptime_info"
echo "Free Memory: $memory_free"
echo "Free Disk Space: $disk_free"
chmod +x system_info.sh
./system_info.sh
次のような出力が表示されるはずです (システム固有の値が表示されます)。
System Information Report
=========================
Date: 2023-11-20
Time: 14:30:25
Hostname: labex
OS Type: Linux
Kernel Version: 5.15.0-1015-aws
Uptime: up 2 hours, 15 minutes
Free Memory: 1.2Gi
Free Disk Space: 15G
変数は、ループで特に役立ちます。これを示すスクリプトを作成しましょう。
countdown.sh という名前の新しいファイルを作成します。#!/bin/bash
## Get countdown start value from user
echo "Enter a number to start countdown:"
read count
## Validate that input is a number
if [[ ! $count =~ ^[0-9]+$ ]]; then
echo "Error: Please enter a valid number"
exit 1
fi
## Perform countdown
echo "Starting countdown from $count:"
while [ $count -gt 0 ]; do
echo $count
count=$((count - 1))
sleep 1
done
echo "Blast off!"
chmod +x countdown.sh
./countdown.sh
スクリプトは、入力した数字からカウントダウンし、各数字を出力し、最後に「Blast off!」と表示します。
これらの例は、Bash スクリプト内のさまざまなコンテキストで変数がどのように使用され、それらをより動的で柔軟にするかを示しています。
この最終ステップでは、Bash の変数のスコープを探り、Bash が提供する特殊変数について学びます。
Bash では、変数はさまざまなスコープを持つことができ、アクセスできる場所が決定されます。
変数のスコープを示すスクリプトを作成しましょう。
variable_scope.sh という名前の新しいファイルを作成します。#!/bin/bash
## Global variable
global_var="I am a global variable"
## Function that demonstrates variable scope
demo_scope() {
## Local variable
local local_var="I am a local variable"
## Access global variable
echo "Inside function: global_var = $global_var"
## Access local variable
echo "Inside function: local_var = $local_var"
## Modify global variable
global_var="Global variable modified"
}
## Main script
echo "Before function call: global_var = $global_var"
## This will fail because local_var doesn't exist yet
echo "Before function call: local_var = $local_var"
## Call the function
demo_scope
## After function call
echo "After function call: global_var = $global_var"
## This will fail because local_var is only accessible within the function
echo "After function call: local_var = $local_var"
chmod +x variable_scope.sh
./variable_scope.sh
次のような出力が表示されるはずです。
Before function call: global_var = I am a global variable
Before function call: local_var =
Inside function: global_var = I am a global variable
Inside function: local_var = I am a local variable
After function call: global_var = Global variable modified
After function call: local_var =
注意点:
global_var は、関数の内側と外側の両方でアクセスできます。local_var は、関数内でのみアクセスできます。Bash は、特定の情報を保持するいくつかの特殊変数を提供します。それらのいくつかを探ってみましょう。
special_variables.sh という名前の新しいファイルを作成します。#!/bin/bash
## Special variables demonstration
echo "Script name: $0"
echo "Process ID: $$"
echo "Number of arguments: $#"
echo "All arguments: $@"
echo "Exit status of last command: $?"
echo "Current user: $USER"
echo "Current hostname: $HOSTNAME"
echo "Random number: $RANDOM"
## Function to demonstrate positional parameters
show_params() {
echo "Function received $## parameters"
echo "Parameter 1: $1"
echo "Parameter 2: $2"
echo "Parameter 3: $3"
}
## Call the function with parameters
echo -e "\nCalling function with parameters:"
show_params apple banana cherry
## Demonstrate positional parameters to the script
echo -e "\nScript positional parameters:"
echo "Parameter 1: $1"
echo "Parameter 2: $2"
echo "Parameter 3: $3"
chmod +x special_variables.sh
./special_variables.sh arg1 arg2 arg3
次のような出力が表示されるはずです。
Script name: ./special_variables.sh
Process ID: 12345
Number of arguments: 3
All arguments: arg1 arg2 arg3
Exit status of last command: 0
Current user: labex
Current hostname: labex
Random number: 23456
Calling function with parameters:
Function received 3 parameters
Parameter 1: apple
Parameter 2: banana
Parameter 3: cherry
Script positional parameters:
Parameter 1: arg1
Parameter 2: arg2
Parameter 3: arg3
環境変数は、シェルとプログラムの動作に影響を与える特殊な変数です。それらを探るスクリプトを作成しましょう。
environment_variables.sh という名前の新しいファイルを作成します。#!/bin/bash
## Display common environment variables
echo "HOME directory: $HOME"
echo "Current user: $USER"
echo "Shell: $SHELL"
echo "Path: $PATH"
echo "Current working directory: $PWD"
echo "Terminal: $TERM"
echo "Language: $LANG"
## Creating and exporting a new environment variable
echo -e "\nCreating a new environment variable:"
MY_VAR="Hello from environment variable"
export MY_VAR
echo "MY_VAR = $MY_VAR"
## Demonstrate that child processes inherit environment variables
echo -e "\nAccessing environment variable from a child process:"
bash -c 'echo "Child process sees MY_VAR = $MY_VAR"'
## Remove the environment variable
echo -e "\nRemoving the environment variable:"
unset MY_VAR
echo "MY_VAR = $MY_VAR (should be empty)"
chmod +x environment_variables.sh
./environment_variables.sh
さまざまな環境変数が表示され、それらの作成、アクセス、および削除の方法を示す出力が表示されるはずです。
このステップでは、Bash での変数のスコープの仕組みを示し、スクリプト内で役立つ情報を提供する特殊変数について紹介しました。
この実験では、Bash スクリプトで変数を使用するための基本を学びました。以下の実践的な経験を積みました。
これらのスキルは、Bash スクリプトの基礎を形成し、より洗練された強力なスクリプトを作成できるようになります。変数は、スクリプトを動的で再利用可能にするための不可欠なツールであり、さまざまな入力とシナリオに適応できるようにします。
Bash スクリプトの旅を続ける際には、次の重要な点を覚えておいてください。
これらのスキルにより、タスクを自動化し、システムを管理するための、より複雑な Bash スクリプトを作成する準備が整いました。