LoginSignup
10
13

More than 5 years have passed since last update.

shellスクリプトを書きたくなったときのための覚え書き

Last updated at Posted at 2013-03-20

コメントの書き方

# コメントは「シャープ」で始める

スクリプト指定のために冒頭に必要な記述(必ず必要)

#!/bin/sh

シェル変数の宣言

svar1=value1

変数威名svar1を定義して、値「value1」を代入する。

※ 「=」の前後にスペースを空けてはいけない

文字列の宣言

空白文字やメタキャラクタを含んだ文字列を代入するときにはクオーテーション「'」かダブルクオーテーション「"」で囲みます。

svar1='example of value'

変数の参照

変数を参照するときには変数名の前に「$」を付加する
(シェル出力コマンド echo)

echo 'シェル変数 svar1 の値は' $svar1

if文

if文を書くときにはif 条件 then コマンド fiで囲む。
複数コマンドの時はelif文を使う。
(真偽値は便宜的に、True: 0 False: 1)
以下、簡単な構造例

if condition1
then 
    command1
elif condition2
then
    command2
else
    command3
fi

リダイレクト

 コマンドを実行したときにその出力をファイルに書き込みたいときにダイレクトとリダイレクトを用いる。

出力先をファイルへ

$ command > file.txt

出力先をファイルへ(追記)

$ command >> file.txt

入力元の切り替え(1行)

$ command < input

入力元の切り替え(複数行)

$ command << input

※ 標準出力と標準エラー出力をリダイレクトで強制的に出力しない方法。

$ command > /dev/null 2>&1

その他よく使うコマンド(その内追記)

・case文
・while文
・until文
・for文
・break文
・exit文

参考ページ

日経Linux: シェル・スクリプト


10
13
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
10
13