3つのスクリプト型言語の変数の違いを理解する
- Shell Script : Linuxを運用する上では必須
- PowerShell : 主にWindowsで利用。オープンソース化でLinuxやmacOSでも使える
- Python : データ分析やAI/ML系で人気のスクリプト
環境に合わせて3つのスクリプト型言語を使っていると、色々混乱してくるので忘備録を兼ね、まとめてみた。
変数の宣言・定義
ShellScript.sh
User:~$ name='Mash'
User:~$ echo $name
Mash
User:~$ name=Mash
User:~$ echo $name
Mash
User:~$ $name
コマンド 'Mash' が見つかりません。
Shell Script
- 変数名と値の間の "=" の両脇にスペースを入れてはダメ
- 変数の値が文字の時でも、クォーテーションの有る無しに関わらず定義可能
- 変数 $name を展開するためにはechoが必要
PowerShell.ps1
PS C:\Mash> $name = 'Mash'
PS C:\Mash> $name = Mash
Mash: The term 'Mash' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
PS C:\Mash> $name
Mash
PS C:\Mash> Write-Host $name
Mash
PowerScript
- 変数の頭に$が必要
- 値にはシングルクォーテーションもしくはダブルクォーテーションが必要
- 変数 $name の展開は、変数をそのまま、もしくはWrite-Hostなどのコマンドで表示する両方のパターンに対応
Python.py
>>> name = 'Mash'
>>> name = Mash
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Mash' is not defined. Did you mean: 'hash'?
>>> name = 'Mash'
>>> name
'Mash'
>>> print(name)
Mash
Python
- 変数をする際に$のような記号は不要
- 変数に文字を指定するときは必ずクォーテーション もしくは ダブルクォーテーションが必要
- 変数 $name の展開は、変数をそのまま、もしくは print( ) などのコマンドで表示する両方のパターンに対応
変数に入れた数値の計算
ShellScript.sh
User:~$ number1=4
User:~$ number2=2
User:~$ echo $((number1 + number2))
6
User:~$ echo $((number1 * number2))
8
User:~$ echo $((number1 / number2))
2
User:~$ echo $((number1 - number2))
2
User:~$ $number1 + $number2
1: コマンドが見つかりません
User:~$ echo ($number1 + $number2)
-bash: 予期しないトークン `$number1' 周辺に構文エラーがあります
- 変数1 + 変数2 のような式では計算できない。
PowerShell.ps1
PS C:\Mash> $number1 = 1
PS C:\Mash> $number2 = 1
PS C:\Mash> $number1 + $number2
2
Python.py
>>> number1 = 1
>>> number2 = 1
>>> number1 + number2
2
変数と変数、変数とテキストの結合
ShellScript.sh
User:~$ str1="Scripting"
User:~$ str2=" is intersting!"
User:~$ str=$str1$str2
User:~$ echo $str
Scripting is intersting!
User:~$ str1="Scripting"
User:~$ str="${str1} is intersting!"
User:~$ echo $str
Scripting is intersting!
- 変数とテキストを結合する際は、変数を{ }で囲んでテキストの中に入れる
PowerShell.ps1
PS C:\Mash> $str1 = "Scripting"
PS C:\Mash> $str2 = " is interesting"
PS C:\Mash> $str = $str1 + $str2
PS C:\Mash> $str
Scripting is interesting
PS C:\Mash> $str1 = "Scripting"
PS C:\Mash> $str = $str + " is interesting"
Scripting is interesting
- 数字と同じように+記号で結合できる
- 前か後ろにスペースを入れておく必要あり。例では" is"のように後ろに入れている
Python.py
>>> str1 = 'Scripting'
>>> str2 = ' is interesting'
>>> str = str1 + str2
>>> str
'Scripting is interesting'
>>> str = str1,str2
>>> str
('Scripting', ' is interesting')
>>> str = str1 + ' is interesting'
>>> str
'Scripting is interesting'
結論
- PowerShell と Python は変数の定義方法、数値計算、文字列の結合についてほぼ同じように扱える
- Shell Script は 異なっているので注意が必要