0
0

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 1 year has passed since last update.

shell script備忘録

0
Last updated at Posted at 2024-02-10

忘れては調べてを繰り返しているので、
shell scriptの構文を備忘録としてまとめる。
bashを想定。

コマンドを複数行に分けて記載する方法

行末に\をつける

curl -X GET "test.com" \
-H 'Content-Type: application/json' \
-d '{"id": 1, text: "test"}'

変数の扱い

#初期化
##=の前後にスベースを入れてはいけない
test_var="qiita"

#数値計算
##shell scrptでは通常変数はすべて文字列として扱われるため、
##数値として扱う場合は以下のように記載する必要がある
cnt=0
# cnt=$(($cnt + 1)) ※非推奨
cnt=$((cnt + 1))

#配列
##一括初期化
array_str=("sh" "bash")

##一要素ずつ初期化
array_str2[0]="sh"
array_str2[1]="bash"

#コマンド出力を変数に格納(pwdの場合、$PWD)
cmd_result=$(pwd)

if

#基本
if [ <条件> ] ;then
    <処理>
elif [ <条件> ] ;then
    <処理>
else
    <処理>
fi

for

continue, breakが使える

# 基本
for <変数> in <値リスト>
do
    <処理>
done

# 10回繰り返し
for i in {1..10}
do
    echo $i
done

# seqを利用
N=10
for i in $(seq 1 $N)
do
    echo $i
done

# ""あるなしで挙動が異なるので注意
# (変数の展開の挙動なのでforに限った話ではない)
# ※下の配列を使う方法を推奨
chars="a b"
for c in $chars
do
    echo c
done
#> a
#> b

for c in "$chars"
do
    echo c
done
#> a b


# ※bashの場合配列が使うことができ、
# スペースの有無に関係なく動くため推奨とのコメントを頂いたため追記
chars=("a" "b")
for c in "${chars[@]}"
do
    echo c
done
#> a b
# 基本2
for ((<初期化>; <条件>; <式>))
do
    <処理>
done

# 例
for ((i=1; i<10; i++))
do
    echo $i
done

関数

# 定義
function func_test() {
    # 引数は$xで受け取り
    # 返り値を標準出力として渡す
    echo "hello, $1"
}

# 呼び出し
func_test "qiita"

# 呼び出し(返り値受け取り)
result=$(func_test "qiita")

`` と $()

コマンド結果の展開をしたい時、``より$()を使用することを推奨とのこと。
※理由は調べ中

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?