Bash での変数の代入と再代入の方法

ShellBeginner
オンラインで実践に進む

はじめに

このチュートリアルでは、人気のシェルスクリプト言語である Bash で変数を割り当てたり、再割り当てしたりするプロセスを説明します。変数は、Bash スクリプトの基本的な構成要素であり、データを保存し操作するために使用されます。この実践的な実験(Lab)では、変数を宣言し、値を割り当て、コマンドやスクリプトで使用する方法を学びます。このチュートリアルを終える頃には、Bash で変数を効果的に扱う方法をしっかりと理解し、より強力で柔軟なスクリプトを作成できるようになるでしょう。

Bash 変数の作成と割り当て

Bash では、変数はスクリプト内で後からアクセスして変更できるデータを保存できます。まず、簡単な変数を作成し、それに値を割り当てることから始めましょう。

LabEx 環境で新しいターミナルを開きます。/home/labex/project ディレクトリにいるはずです。

Bash で変数に値を割り当てるには、次の構文を使用します。

variable_name=value

等号の周りにスペースを入れてはいけないことに注意してください。

最初の変数を作成しましょう。

  1. ターミナルで、次のコマンドを入力し、Enter キーを押します。
name="John"
  1. 変数の値を表示するには、ドル記号 ($) を前に付けた変数名とともに echo コマンドを使用します。
echo $name

次のような出力が表示されるはずです。

John
  1. 変数名を二重引用符で囲むこともできます。
echo "My name is $name"

出力:

My name is John
  1. 同じ変数に新しい値を再割り当てするには、代入演算子 (=) をもう一度使用するだけです。
name="Alice"
echo "My name is $name"

出力:

My name is Alice

変数命名規則

Bash で変数を作成する際は、次の命名規則に従ってください。

  • 変数名には、文字、数字、およびアンダースコアを含めることができます。
  • 変数名は、文字またはアンダースコアで始める必要があります。
  • 変数名は大文字と小文字を区別します。
  • 変数名にスペースは使用できません。

変数を使った練習をするために、ファイルを作成しましょう。WebIDE で、プロジェクトディレクトリに variables.sh という名前の新しいファイルを作成します。

  1. IDE の「New File」アイコンをクリックします。
  2. ファイル名を variables.sh とします。
  3. ファイルに次のコードを追加します。
#!/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"
  1. Ctrl+S を押すか、File → Save をクリックしてファイルを保存します。

  2. ターミナルで次のコマンドを実行して、スクリプトを実行可能にします。

chmod +x variables.sh
  1. 次のコマンドでスクリプトを実行します。
./variables.sh

次のような出力が表示されるはずです。

First name: John
Last name: Doe
Age: 25
Updated first name: Jane

これは、変数の作成、値の割り当て、および新しい値の再割り当ての方法を示しています。

変数の値と文字列操作の操作

このステップでは、文字列操作や算術計算など、Bash で変数の値を操作するさまざまな方法を探ります。

文字列操作

Bash は、変数に格納された文字列値を操作するためのいくつかの方法を提供します。

  1. プロジェクトディレクトリに 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"
  1. ファイルを保存し、実行可能にします。
chmod +x string_operations.sh
  1. スクリプトを実行します。
./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 では、変数を使用した算術演算も実行できます。

  1. プロジェクトディレクトリに 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"
  1. ファイルを保存し、実行可能にします。
chmod +x arithmetic_operations.sh
  1. スクリプトを実行します。
./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

変数へのユーザー入力の読み取り

変数には、ユーザーが提供した入力を格納することもできます。ユーザーに入力を求めるスクリプトを作成しましょう。

  1. 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."
  1. ファイルを保存し、実行可能にします。
chmod +x user_input.sh
  1. スクリプトを実行します。
./user_input.sh
  1. プロンプトが表示されたら、名前と年齢を入力します。スクリプトは挨拶を表示し、おおよその誕生年を計算します。

このステップでは、文字列操作、算術計算、ユーザー入力の読み取りなど、変数を使用したさまざまな操作を実行する方法を示しました。

スクリプトとコマンドでの変数の使用

このステップでは、Bash スクリプトとコマンドで変数を効果的に使用する方法を探ります。さまざまなシナリオでの変数の使用を示す実用的なスクリプトを作成します。

変数を使用した基本的なスクリプトの作成

ショッピングカート内の商品の合計金額を計算するスクリプトを作成しましょう。

  1. プロジェクトディレクトリに 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
  1. ファイルを保存し、実行可能にします。
chmod +x shopping_cart.sh
  1. スクリプトを実行します。
./shopping_cart.sh

次のような出力が表示されるはずです。

Shopping Cart:
-------------
Laptop: $999
Headphones: $149
Mouse: $25
-------------
Total: $1173
Discount (10%): -$117
Final Total: $1056

コマンド置換を使用した変数の使用

コマンド置換を使用すると、コマンドの出力を取得して変数に格納できます。これを示すスクリプトを作成しましょう。

  1. 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"
  1. ファイルを保存し、実行可能にします。
chmod +x system_info.sh
  1. スクリプトを実行します。
./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

ループでの変数の使用

変数は、ループで特に役立ちます。これを示すスクリプトを作成しましょう。

  1. 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!"
  1. ファイルを保存し、実行可能にします。
chmod +x countdown.sh
  1. スクリプトを実行します。
./countdown.sh
  1. プロンプトが表示されたら、小さな数字 (5 など) を入力します。

スクリプトは、入力した数字からカウントダウンし、各数字を出力し、最後に「Blast off!」と表示します。

これらの例は、Bash スクリプト内のさまざまなコンテキストで変数がどのように使用され、それらをより動的で柔軟にするかを示しています。

変数のスコープと特殊変数

この最終ステップでは、Bash の変数のスコープを探り、Bash が提供する特殊変数について学びます。

変数のスコープの理解

Bash では、変数はさまざまなスコープを持つことができ、アクセスできる場所が決定されます。

  1. グローバル変数: これらはスクリプト全体でアクセスできます。
  2. ローカル変数: これらは特定の関数またはブロック内でのみアクセスできます。

変数のスコープを示すスクリプトを作成しましょう。

  1. 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"
  1. ファイルを保存し、実行可能にします。
chmod +x variable_scope.sh
  1. スクリプトを実行します。
./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 は、特定の情報を保持するいくつかの特殊変数を提供します。それらのいくつかを探ってみましょう。

  1. 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"
  1. ファイルを保存し、実行可能にします。
chmod +x special_variables.sh
  1. いくつかの引数を使用してスクリプトを実行します。
./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

環境変数

環境変数は、シェルとプログラムの動作に影響を与える特殊な変数です。それらを探るスクリプトを作成しましょう。

  1. 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)"
  1. ファイルを保存し、実行可能にします。
chmod +x environment_variables.sh
  1. スクリプトを実行します。
./environment_variables.sh

さまざまな環境変数が表示され、それらの作成、アクセス、および削除の方法を示す出力が表示されるはずです。

このステップでは、Bash での変数のスコープの仕組みを示し、スクリプト内で役立つ情報を提供する特殊変数について紹介しました。

まとめ

この実験では、Bash スクリプトで変数を使用するための基本を学びました。以下の実践的な経験を積みました。

  • 変数の作成と値の割り当て
  • 文字列操作と算術計算の操作
  • スクリプトとコマンドでの変数の使用
  • 変数のスコープの理解と特殊変数の操作

これらのスキルは、Bash スクリプトの基礎を形成し、より洗練された強力なスクリプトを作成できるようになります。変数は、スクリプトを動的で再利用可能にするための不可欠なツールであり、さまざまな入力とシナリオに適応できるようにします。

Bash スクリプトの旅を続ける際には、次の重要な点を覚えておいてください。

  • 常に説明的な変数名を選択する
  • 関数を記述する際には、変数のスコープに注意する
  • スクリプト内で役立つ情報にアクセスするために、特殊変数を使用する
  • 設定とカスタマイズには、環境変数を利用する

これらのスキルにより、タスクを自動化し、システムを管理するための、より複雑な Bash スクリプトを作成する準備が整いました。