Skip to content

Instantly share code, notes, and snippets.

@chuck0523
Created November 21, 2015 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuck0523/6203205c1be0bd80b012 to your computer and use it in GitHub Desktop.
Save chuck0523/6203205c1be0bd80b012 to your computer and use it in GitHub Desktop.
#! /bin/bash
# ハロワ
# echo "hello world!"
# 変数
h="hello"
w="world"
# echo $h $w
# 数値
x=10
echo $x
echo $x + 2
echo `expr $x + 2` # 演算には`expr `が必要
echo `expr $x \* 2` # 乗算記号の前にはバックスラッシュが必要
# readonly
readonly FILE_NAME="hello.sh"
FILE_NAME="world.sh" # エラー
# 配列
a=(2 4 6)
echo $a # 先頭要素
echo ${a[1]} # 添字を使用するときは、波カッコで囲う
echo ${a[@]} # 全要素
echo ${#a[@]} # 要素数
a[2]=10 # 表示と違い、代入では波括弧は不要
echo ${a[@]}
a+=(20 30)
echo ${a[@]}
d=(`date`)
echo ${d[2]}
# 条件式
# 正常終了(0)
# 数値の評価
test 1 -eq 2; echo $?
test 1 -eq 1; echo $?
# eq = equal
# ne = not equal
# gt = >
# ge = >=
# lt = <
# le = <=
# 文字列比較
# = equal
# != not equal
# ファイルの比較
# -nt = newer than
# -ot = older than
# -e = is exist
# -d = is direcrtory
test -e "hello.sh"; echo $?
# 論理演算子
# -a AND
# -o OR
# ! NOT EQUAL
test 1 -eq 1 -a 2 -eq 2; echo $?
# if文
x=70
if test $x -gt 60
then
echo "ok!"
fi
# 上記の省略形
if [ $x -gt 60 ]; then
echo "ok!"
fi
y=20
if [ $y -gt 70 ]; then
echo "good"
elif [ $y -gt 40 ]; then
echo "soso"
else
echo "ng..."
fi
# コマンド引数
echo $0 # ファイル自身を表す
echo $1 # 第一引数
echo $2 # 第二引数
echo $@ # 全引数
echo $# # 引数の個数
# 標準入出力
# read
while :
do
read key
echo "you pressed $key"
if [ $key = "end" ]; then
break
fi
done
select option in CODE DIE
do
echo "you pressed $option"
break
done
# ファイルからの読み込み
i=1
while read line
do
echo "$i: $line"
i=`expr $i + 1`
done <$1
# 関数
function hello() {
echo "hello $1 and $2"
}
hello Mike Tom
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment