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?

シェルスクリプトの書き方

Last updated at Posted at 2025-01-20

コメント(コメントアウト)

#!/bin/bash

#「#」を行頭に入力するとその行をコメントとして記述できる
# コマンドも「#」とするとコメントとなる。これを「コメントアウト」という
# echo hello

複数コマンドの記述

#!bin/bash

# コマンドを複数に分けて書くことができる
echo hello
echo world

=> hello
=> world

# 「;」を利用して複数コマンドを一行にまとめて書くことができる
echo hello; echo world

=> hello
=> world

# 一つのコマンドを複数行にわたって書くこともできる
echo \
hello world

=> hello world

シェル変数

Rubyなどのプログラミング言語同様、変数を設定することができる。これをシェル変数と呼ぶ。

代入

greeting=hello

# 「=」の前後にスペースを入れてはいけない
# これはNG
greeting = hello

# 変数に利用できるのは「アルファベット」「_」「数字」の三種類。数字を頭に持ってきてはいけない
_greeting=hello
greeting_1=hello
first_greeing=hello

# これはNG
1greeting=hello

参照

# 参照するときは「$」 を定義した変数の先頭につける
greeting=hello
echo $greeting

=> hello

変数展開

変数を他の文字列と連結する

greeting=hello
echo ${hello}_world

=> hello_world

クォーティング

変数に文字列を渡すときに通常の代入ではスペース区切りの文字列を渡すことができない。その場合、「シングルクォート」「ダブルクォート」で代入したい文字列を囲う。

# これはNG
greeting=hello world

# 「シングルクォート」で囲う
greeting='hello world'

# 「ダブルクォート」で囲う
greeting="hello world"
echo $greeting

=> hello world

#「シングルクォート」「ダブルクォート」の違い 「変数展開できるかどうか」

# 「シングルクォート」だと変数展開できない
greeting='hello world'
echo 'hi! $greeting'

# 変数展開されず「$」が文字として認識される
=> hi! $greeting

# 「ダブルクォート」だと変数展開される
greeting='hello world'
echo "hi! $greeting"

=> hi! hello world

コマンド置換

コマンドの出力結果をシェルスクリプトで利用できる仕組み。

# ファイル名を日付にする
file_name=$(date '+%Y-%m-%d')
touch "$file_name"

# バッククォートでっ囲ってもOK、だけど$()の方がよく使われる
file_name=`(date '+%Y-%m-%d')`

*追記予定

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