2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Shellの基本を学ぶ(1)シェルスクリプト

2
Last updated at Posted at 2019-03-13

私は、Shellプログラムに弱い。見様見真似で書けるけど、理解しているとは程遠い。簡単なシェルプログラムを書くタスクをする必要があったので、この際まとめて勉強することにした。少しづつ、書いていきたい。これは、Pluralsights のとてもよかったコースの自分用勉強メモです。

Shell Script

Shellのコマンドが書かれたファイルで上から実行される。#!/bin/sh という記述が無くても実行できる。コメントは、#

hw

# Print Hello World.
echo Hello World

実行可能にする

ファイルは実行可能にする必要がある。chmod コマンドを使って実行可能にする。

$ chmod u+x hw
$ ./hw
Hello World

ダブルクオートとかシングルクオートとか無しで動くのね。

ファイル名

重複しないようにする。type コマンドが便利

$ type ls
ls is /bin/ls
$ type some
-bash: type: some: not found

パスを通す

パスを通すと普通のコマンドのように実行できる。レイジーだから余計なのをタイプしたくないらしい。

$ PATH=$PATH:/User/ushio/Codes/Bash/bin
$ hw
Hello World

Substitution

Substitution というコンセプトがサクッと出てきたけど、実は十分理解できていないので、理解してみる。

Command Substitution

Command Substitution はコマンドの実行結果で該当のコマンドを置き換える方法。$(command)`command` という方法がある。両方だったのね。例えば

$ ls
bin		hello_world.sh	tn.sh
$ echo $(ls) 
bin hello_world.sh tn.sh

コマンドの実行結果で置き換えているからか、フォーマットはされないけど、実行結果で置き換えられています。

Command Substitution

Variable Substitution

変数は、高級言語のそれでは無くて、ターゲットの文字列を置き換えるという感じの様子。$ をつけることで、変換される。

$ variables=23
$ echo variables
variables
$ echo $variables
23

ちなみに、$variables${variables} の簡単なフォームです。

代入ミスの振る舞いの違い

最初のものは、VARIABLEというコマンドを実行しようとする。2つめのは、VARIABLE という変数に、"" をアサインして、value というコマンドを実行しようとする。(エラーメッセージに注意)

$ VARIABLE =value
-bash: VARIABLE: command not found
$ VARIABLE= value
-bash: value: command not found

Whilte space

空白の扱いはこんな感じです。" でくくると、ホワイトスペースがキープされますが、くくらないと、ホワイトスペースは、1つになります。

$ hello="A B  C   D"
$ echo "$hello"
A B  C   D
$ echo $hello
A B C D

シングルクオート

動きません。そのままに

$ echo '$hello'
$hello

複数の変数代入

ホワイトスペースで区切られていたら、複数の変数代入を1行で書けます。

$ var1=21 var2=22 var3=23
$ echo "var1=$var1 var2=$var2 var3=$var3"
var1=21 var2=22 var3=23

ホワイトスペースには、ダブルクオートが必要

真ん中のは、other_numbers=1 がSubstitute 指定で、2 というコマンドを実行しようとしている。

$ numbers="one two three"
$ other_numbers=1 2 3
-bash: 2: command not found
$ other_numbers="1 2 3"

ホワイトスペースのキャンセル

バックスラッシュで

$ mixed_bag=2\ ---\ Whatever
$ echo $mixed_bag
2 --- Whatever

未代入/Unsetは何もなしに

$ echo "uninitialized_variables = $uninitialized_variable"
uninitialized_variables =
$ uninitialized_variables=
$ echo $uninitialized_variables

$ uninitialized_variables=23
$ echo $uninitialized_variables
23
$ unset uninitialized_variables
$ echo $uninitialized_variables

変数のネーミング

変数は、Case sensitive で、全部大文字のが、pre-defined のもので、小文字スタートがそうではないもの。

Variable Substitution

Parameter Substitution

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?