シェルスクリプト(bash)の基本 ~チュートリアル~

目次


目的
シェルとは
シェルスクリプトとは
UNIX系OS(Linux, Mac)における基礎知識
パス(絶対パス・相対パス)
プログラミング言語は、英語の命令文に相当
ファイル名に日本語やスペースを用いない
bash基本
文字の表示(コマンド:echo)
Brace Expansionの使い方
変数(コマンド:変数=〇〇)
変数の定義
変数の利用
変数の配列処理
配列
配列の定義
配列の利用
現在いるディレクトリの確認(コマンド:pwd)
端末(ターミナル)の画面をクリア(コマンド:clear)
標準入力から変数を定義
条件分岐:If文(コマンド:if)
条件分岐:Case文(コマンド:case)
四則演算
リダイレクト(コマンド:> or >>)
ファイル内容出力(コマンド:cat)
ファイルのリスト一覧確認(コマンド:ls)
カウント(コマンド:wc -l)
パイプ [ | ](コマンド:|)と検索(コマンド:grep)
テキストファイルの作成(コマンド:touch)
フォルダの作成(コマンド:mkdir)
ファイル・フォルダのコピー(コマンド:cp)
ファイルをコピー
フォルダをコピー:オプション(-r)必須
ファイル・フォルダの移動(コマンド:mv)
ディレクトリ移動(コマンド:cd)
ファイル・フォルダの削除(コマンド:rm)
ファイルの削除
フォルダの削除:オプション(-r)必須
反復処理:For文(コマンド:for)
反復処理:While文(コマンド:while)
関数(コマンド:function)
先頭の表示(コマンド:head)
末尾の表示(コマンド:tail)
ソート処理(コマンド:sort)
重複削除(コマンド:uniq)
文字列の切り出し・抽出(コマンド:cut)
区切り文字を指定して抽出
-d: 区切り文字指定
-f: フィールドの指定
文字のインデックスを指定して抽出
-c: 先頭からの文字数
文字列の置換(コマンド:sed)
数字の連番(コマンド:seq)
コマンドのレファレンスマニュアルを表示(コマンド:man)
ワイルドカード [ * ] (コマンド:*)


目的

  • UNIX系OS(Linux, Mac)における基礎知識をおさえる
  • シェルスクリプトであるbash(バッシュ)の基本的な使い方をおさえる

シェルとは

シェルとは、オペレーティングシステム(OS)と対話するためのインターフェースであり、ユーザからの命令(コマンド)を制御する環境である。

イメージとしては、Linuxの核となるカーネルを覆っている殻がシェルであり、ユーザからの命令(コマンド)を解釈し、カーネルが分かるように翻訳して渡す。カーネルからの出力は、人間の分かるように翻訳して返すといった人とOSの橋渡し的存在である。

カーネルは、CPUやメモリ、ハードディスクなどのハードウェアとソフトウェアを仲介するプログラムで、OSの中核部分を担っている。

シェルには、様々な種類があるがLinuxで最も一般的なシェルは、「Bourne Againシェル(bash)」である。

シェルスクリプトとは

シェルスクリプトとは、シェルによって解釈・実行される一連の処理を記述したスクリプトである。

スクリプト(script)は、PCに実行させたい処理を記述した、いわば「台本」であり、この台本をテキストエディタで記載したものがシェルスクリプトである。

シェルスクリプトを用いることによって、①作業を自動化したり、②作業の結果を記録したり、③複数作業を複数のコマンドでまとめて処理することができる。また、脳画像解析ではシェルスクリプトでファイル操作をしたり、ソフトウェアを制御することが多く、ある程度の知識・技術を身に着けておく必要がある。

UNIX系OS(Linux, Mac)における基礎知識

UNIX系OS(Linux, Mac)におけるプログラミングで、最低限知っておいた方がよい知識を紹介する。

パス(絶対パス・相対パス)

パス(Path)は、日本語で「経路」であり、ファイル・フォルダがどのディレクトリ(フォルダ)に保存されているのかを示す道筋、いわば住所のようなものである。(※GUIではフォルダ、CUIではディレクトリと呼ぶ。厳密には異なるが、どちらも基本的には同じと思ってよい。)

パスには、「絶対パス」と「相対パス」がある。

絶対パス

絶対パスは、フルパスともいい、ルートディレクトリ(/)と呼ばれる階層構造の頂点からターゲットとなるファイル・フォルダまでの経路を表す。

相対パス

相対パスは、ユーザが作業をしているディレクトリからターゲットとなるファイル・フォルダまでの経路を表す。

パスの表記を簡略化するために、次の記号がある。

  • シングルドット( . ):現在(作業中)のディレクトリ
  • ダブルドット( .. ):作業ディレクトリの上のディレクトリ(親ディレクトリ)
  • チルダ( ~ ):ホームディレクトリ(例:/home/neuro)

プログラミング言語は、英語の命令文に相当

シェル(例:bash)は、PCと会話するための「言語」であり、文法は英語に似ている。

シェルで使用するコマンドは、基本的に「動詞」であると考えると、理解しやすい。また、シェルでは英語でいう基本文型である「第3文型(SVO)」や「第4文型(SVOO)」で命令をだす。例えば、ディレクトリ移動(cd)やフォルダ作成(mkdir)は第3文型、コピー(cp)やファイル/フォルダ移動(mv)は第4文型をとる。

具体的には、「neuroディレクトリ移動」と命令する場合には、ディレクトリ移動コマンド(cd)を用いて次のように記述する。

cd neuro/

また、「file.txtをneuroディレクトリ移動」と命令する場合には、ファイル/フォルダ移動コマンド(mv)を用いて次のように記述する。

mv  file.txt neuro/

ファイル名に日本語やスペースを用いない

脳画像解析ソフトによっては、全角文字を使うことでエラーが発生する場合がある。また、日本語ファイル名にしてしまうと、コマンドをうったり、コードを書くときに手間である。シェルで全角スペースを使うことでエラーになることもあり、面倒ごとをさけるためにも基本的に「半角文字」で生きる。

シェルでは、空白は「区切り」と認識する。例えば、「file 001.txt」というファイルがあり、このファイルをneuroフォルダに移動させる場合、次のコマンドになる。

mv file 001.txt neuro/

この時、シェルでは「file」と「001.txt」それぞれのファイルをneuroフォルダに移動するのだなと認識してしまう。このようなことにならぬよう、空白は用いない。もしも空白を用いたい場合、代わりにアンダースコア( _ )を用いるとよい。

つまり、「file_001.txt」というファイル名で、このファイルをneuroフォルダに移動させる場合、以下のように記述でき、正常に動作する。

mv file_001.txt neuro/

bash基本

これより先は、実際にbashコマンドとその使い方について解説していく。

参考サイト:https://learnxinyminutes.com/docs/bash/

文字の表示(コマンド:echo)

# 「Hello world!」という文字列を表示
echo Hello world!

Hello world!

# 2行のコマンドを1行で表記するには、セミコロン(;)でつなぐ
echo 'This is the first line'; echo 'This is the second line'

This is the first line
This is the second line

# 正規表現を用いて表示
# "\n": 改行
# "-e": 正規表現として認識(例: 「\n」は改行であると認識)
Contents="Hello world!"
echo -e "START OF FILE\n$Contents\nEND OF FILE"

START OF FILE
Hello world!
END OF FILE

Brace Expansionの使い方

# 1から10までの数字を簡単なコマンドで表示
echo {1..10}

1 2 3 4 5 6 7 8 9 10

# aからzまでのアルファベットを簡単なコマンドで表示
echo {a..z}

a b c d e f g h i j k l m n o p q r s t u v w x y z

変数(コマンド:変数=〇〇)

注意:

  1. 変数として利用する際には、変数の前にドルマーク(\$)をつける(例:$変数)
  2. イコール(=)前後にスペースを入れない

変数の定義

# Variableという変数に「Some string」を格納
Variable="Some string"
# イコール(=)前後にスペースを入れるとエラーを起こす
# Variable = "Some string"

変数の利用

# 変数に格納された文字列を表示
echo $Variable

Some string

# 中括弧{}で囲ってもよい
# 変数とその他の文字列を区別したいときに有用(例:Folder/${Variable}/myfolder)
echo ${Variable}

Some string

# ダブルクォーテーション(")で変数($Variable)を囲ってもよい
echo "$Variable"

Some string

# ただし、シングルクォーテーション(')では、不可
# 単なる「$Variable」という文字列として表示される
echo '$Variable'

$Variable

# コマンドの出力を変数に格納し、文字列と共に表示
current_dir=$(pwd)  # 現在いるディレクトリのパスを確認
file_count=$(ls ~ |wc -l)  # ホームディレクトリ内のファイル数をカウント

# 変数を用いて表示
echo "There are ${file_count} in ${current_dir}."

# 変数を用いずに表示
echo "There $(ls ~ |wc -l) are  in $(pwd)"

There are 12 in /home/neuro/Documents/hatena/brain_mri_basic/Bash_basic.
There 12 are in /home/neuro/Documents/hatena/brain_mri_basic/Bash_basic

変数の配列処理

# 配列の長さを表示
echo ${#Variable}

11

# 最初の7文字だけ表示
Length=7
echo ${Variable:0:Length}

Some st

# 最後から5文字を表示
echo ${Variable: -5}

tring

配列

配列の定義

# 6つの要素を持つ配列を定義
array0=(one two three four five six)

配列の利用

注意:
配列のインデックスは、0から始まる。(例:3番目の配列を指定する場合、「${配列変数[2]}」と記載)

# 最初の配列を表示
echo $array0 # => "one"

one

# 要素のインデックスを指定して、最初の配列を表示
echo ${array0[0]}

one

# すべての配列を表示
echo ${array0[@]}

one two three four five six

# 配列の要素数を表示
echo ${#array0[@]}

6

# 3番目の要素の長さを表示
echo ${#array0[2]}

5

# 4番目と5番目の配列を表示
# ${array0[@]:インデックス番号:ほしい配列数}
echo ${array0[@]:3:2}

four five

# すべての配列を1行ずつ表示
for i in "${array0[@]}"; do
	echo "$i"
done

one
two
three
four
five
six

現在いるディレクトリの確認(コマンド:pwd)

# pwdコマンドの出力と文字列を合わせて表示
# $(コマンド)で実現可
echo "I'm in $(pwd)."

I’m in /home/neuro/Documents/hatena/brain_mri_basic/Bash_basic.

# $PWDでもOK
echo "I'm in $PWD."

I’m in /home/neuro/Documents/hatena/brain_mri_basic/Bash_basic.

端末(ターミナル)の画面をクリア(コマンド:clear)

ショートカット:Ctrl/Command + L

# 端末(ターミナル)上に表示されている文字列を、クリア
clear

標準入力から変数を定義

# 変数(Name)に、端末(ターミナル)から文字列を入力
echo "What's your name?"
read Name

端末(ターミナル)で「Neuro」とタイプしてEnter/Returnをした場合。

# 表示
echo Hello, $Name!

Hello, Neuro!

条件分岐:If文(コマンド:if)

# 変数を定義
User='neuro'
# User変数とName変数の中身が同じ場合
Name='neuro'

if [ $Name = $USER ]
then
	echo "Your name is your username"
else
	echo "Your name isn't your username"
fi

Your name is your username

# User変数とName変数の中身が異なる場合
Name='brain'

if [ $Name = $USER ]
then
	echo "Your name is your username"
else
	echo "Your name isn't your username"
fi

Your name isn’t your username

# if notを「!=」で表現
Name='brain'

if [ $Name != $USER ]
then
	echo "Your name isn't your username"
else
	echo "Your name is your username"
fi

Your name isn’t your username

# ANDは「&&」で表現
echo "Always executed" && echo "Only executed if first command does NOT fail"

Always executed
Only executed if first command does NOT fail

# ORは「||」で表現
echo "Always executed" || echo "Only executed if first command fails"

Always executed

# ANDを使ったIf文
Name='Steve'
Age=15

if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then
	echo "This will run if $Name is Steve AND $Age is 15."
fi

This will run if Steve is Steve AND 15 is 15.

# ORを使ったIf文
Name='Zach'

if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
	echo "This will run if $Name is Daniya OR Zach."
fi

This will run if Zach is Daniya OR Zach.

条件分岐:Case文(コマンド:case)

# Variable変数の定義
Variable=1

# Case文の条件分岐
case "$Variable" in
# List patterns for the conditions you want to meet
	0) echo "There is a zero.";;
	1) echo "There is a one.";;
	*) echo "It is not null.";;  # match everything
esac

There is a one.

四則演算

# 和
echo $(( 10 + 5 ))

15

# 差
echo $(( 10 - 5 ))

5

# 積
echo $(( 10 * 5 ))

50

# 商
echo $(( 10 / 5 ))

2

# 剰余
echo $(( 13 % 5 ))

3

リダイレクト(コマンド:> or >>)

# 「Hello world!」という文字列をfile.txtに書き込み・保存
echo Hello world! > "file.txt"

ファイル内容出力(コマンド:cat)

# file.txtの内容を出力
cat file.txt

Hello world!

# file.txtを「>」で上書き
echo Good Bye world! > "file.txt"

# file.txtの内容を出力
cat file.txt

Good Bye world!

# file.txtに「>>」で追記
echo Hello world! > "file.txt"
echo Good Bye world! >> "file.txt"

# file.txtの内容を出力
cat file.txt

Hello world!
Good Bye world!

# lsの出力をリダイレクト
ls > "output_log.txt"

# output_log.txtの内容を出力
cat output_log.txt

Bash_basic.ipynb
file.txt
output_log.txt

# lsのエラー出力をリダイレクト
ls temp 2> "error_log.txt"

# error_log.txtの内容を出力
cat error_log.txt

ls: ‘temp’ にアクセスできません: そのようなファイルやディレクトリはありません

# lsの出力とエラーの両方をリダイレクト
ls > "output_and_error_log.txt" 2>&1

# error_log.txtの内容を出力
cat error_log.txt

ls: ‘temp’ にアクセスできません: そのようなファイルやディレクトリはありません

# lsの出力とエラーの両方をブラックホールに出力
ls > /dev/null 2>&1

ファイルのリスト一覧確認(コマンド:ls)

# ファイルリスト一覧表示
ls

Bash_basic.ipynb file.txt output_log.txt
error_log.txt output_and_error_log.txt

# 詳細表示
ls -l

合計 68
-rw-r–r– 1 neuro neuro 49761 4月 21 20:42 Bash_basic.ipynb
-rw-r–r– 1 neuro neuro 110 4月 21 20:43 error_log.txt
-rw-r–r– 1 neuro neuro 29 4月 21 20:43 file.txt
-rw-r–r– 1 neuro neuro 80 4月 21 20:43 output_and_error_log.txt
-rw-r–r– 1 neuro neuro 41 4月 21 20:43 output_log.txt

# 最終変更時刻でソートして表示
ls -t

output_and_error_log.txt output_log.txt Bash_basic.ipynb
error_log.txt file.txt

# サブディレクトリも含めて再帰的に表示
ls -R

.:
Bash_basic.ipynb file.txt output_log.txt
error_log.txt output_and_error_log.txt

# ファイルかフォルダを区別して表示
# フォルダ名の末尾に、スラッシュ(/)が付く
# フォルダ:[ファイル名]/
ls -F

Bash_basic.ipynb file.txt output_log.txt
error_log.txt output_and_error_log.txt

カウント(コマンド:wc -l)

# file.txtに「>>」で追記
echo Hello world! > "file.txt"
echo Hi world! >> "file.txt"
echo Good Bye world! >> "file.txt"

# file.txtの内容を出力
cat file.txt

Hello world!
Hi world!
Good Bye world!

# file.txtの行数をカウント
wc -l file.txt

3 file.txt

パイプ [ | ](コマンド:|)と検索(コマンド:grep)

# 「Hello world!」という文字列をfile.txtに書き込み・保存
echo Hello world! > "file.txt"

# ファイル一覧を表示
ls

Bash_basic.ipynb file.txt output_log.txt
error_log.txt> output_and_error_log.txt

# 「file」という文字列を持つファイルのみを表示
ls | grep "file"

file.txt

テキストファイルの作成(コマンド:touch)

# file.txtという空のファイルを作成
touch file.txt
# ファイル一覧を確認
ls

file.txt

フォルダの作成(コマンド:mkdir)

# 「myNewDir」というフォルダを作成
mkdir myNewDir
# ファイル一覧を確認
ls

myNewDir

# 「-p」オプションを用いて、サブディレクトリも含めて作成
mkdir -p myNewDir/with/intermediate/directories
# myNewDirフォルダを再帰的に確認
ls -R myNewDir/

myNewDir/:
with

myNewDir/with:
intermediate

myNewDir/with/intermediate:
directories

myNewDir/with/intermediate/directories:

ファイル・フォルダのコピー(コマンド:cp)

ファイルをコピー

# 「Hello world!」という文字列をfile.txtに書き込み・保存
echo Hello world! > "file.txt"

# file.txtをclone.txtとして保存
cp file.txt clone.txt
# clone.txtの内容を表示
cat clone.txt

Hello world!

フォルダをコピー:オプション(-r)必須

# srcDirフォルダを作成
mkdir -p srcDir/myNewDir
# srcDirフォルダにfile.txtを作成
touch srcDir/file.txt

# srcDirフォルダを再帰的に確認
ls -R srcDir/

srcDir/:
file.txt myNewDir

srcDir/myNewDir:

# フォルダを再帰的にコピー
cp -r srcDir/ dstDir/ # recursively copy

# srcDirフォルダをコピーしたdstフォルダ再帰的に確認
ls -R dstDir

dstDir:
file.txt myNewDir

dstDir/myNewDir:

ファイル・フォルダの移動(コマンド:mv)

# srcDirフォルダにfile.txtを作成
touch file.txt
# mvDirフォルダを作成
mkdir mvDir

# 再帰的にファイル一覧を確認
# file.txtにがあることを確認
ls -R

.:
file.txt

./mvDir:

# file.txtをmvDirフォルダに移動
mv file.txt mvDir

# 再帰的にファイル一覧を確認
# file.txtにがmvDirフォルダにあることに注目
ls -R

.:

./mvDir:
file.txt

ディレクトリ移動(コマンド:cd)

# ホームディレクトリに移動
cd ~

# 現在のディレクトリを表示
pwd

/home/neuro

# ひとつ前にいたディレクトリに戻る
cd -

# 現在のディレクトリを表示
pwd

/home/neuro/Documents/hatena/brain_mri_basic/Bash_basic
/home/neuro/Documents/hatena/brain_mri_basic/Bash_basic

# 現在のディレクトリを表示
pwd

# cdDirというフォルダを作成
mkdir cdDir

# cdDirフォルダに移動
cd cdDir

# 現在のディレクトリを表示
pwd

/home/neuro/Documents/hatena/brain_mri_basic/Bash_basic
/home/neuro/Documents/hatena/brain_mri_basic/Bash_basic/cdDir

# 一つ上の階層に移動
cd ..

# 現在のディレクトリを表示
pwd

/home/neuro/Documents/hatena/brain_mri_basic/Bash_basic

ファイル・フォルダの削除(コマンド:rm)

ファイルの削除

# file.txtを作成
touch file.txt

# ファイル一覧を確認
ls | grep "file"

file.txt

# file.txtを削除
rm file.txt

# ファイル一覧を確認し、file.txtが削除されていることを確認
ls | grep "file"  # file.txtは無いため、出力なし

フォルダの削除:オプション(-r)必須

# rmDirというフォルダを作成
mkdir rmDir
# rmDirにfile.txtファイルを作成
touch rmDir/file.txt

# ファイル一覧を再帰的に確認
# rmDirフォルダに注目
ls -R

.:

./rmDir:
file.txt

# rmDirフォルダを削除
rm -r rmDir/

# ファイル一覧を再帰的に確認
# rmDirフォルダがないことに注目
ls -R

.:

反復処理:For文(コマンド:for)

# 1,2,3を順番にVariable変数に格納し、echoコマンドで表示
for Variable in {1..3}
do
	echo "$Variable"
done

1
2
3

# リダイレクトを使って、file1.txtとfile2.txtに文字列を格納
echo Hello world! > "file1.txt"
echo Good Bye world! > "file2.txt"

# file1変数とfile2変数の定義
file1="file1.txt"
file2="file2.txt"

# file1変数, file2変数の順にcatコマンドでファイル内容を表示
for Variable in $file1 $file2
do
	cat "$Variable"
done

Hello world!
Good Bye world!

# テキストファイル(.txt)のみをリスト化し、順次catコマンドで内容を表示
for Variable in $(ls | grep "txt")
do
	cat "$Variable"
done

Hello world!
ls: ‘temp’ にアクセスできません: そのようなファイルやディレクトリはありません
Hello world!
Good Bye world!
Bash_basic.ipynb
error_log.txt
file.txt
output_and_error_log.txt
output_log.txt
Bash_basic.ipynb
file.txt
output_log.txt

反復処理:While文(コマンド:while)

# 無限ループ文。以下では、一度目のループで、ループ終了(break)するようになっている
# breakを取れば、無限ループ
while [ true ]
do
	echo "loop body here..."
	break
done

loop body here…

関数(コマンド:function)

# fooという関数を定義
function foo ()
{
	echo "Run function"
}
# 関数を実行
foo

Run function

# foo2という関数を定義
# $@: すべての引数
# $1: 第1引数
# $2: 第2引数
function foo2 ()
{
	echo "Arguments work just like script arguments: $@"
	echo "And: $1 $2..."
	echo "This is a function"
	return 0
}
# 関数を実行
foo2 arg1 arg2

Arguments work just like script arguments: arg1 arg2
And: arg1 arg2…
This is a function

先頭の表示(コマンド:head)

# 1~50の数字をnum_list.txtに格納
for num in {1..50}
do
	echo "${num}" >> num_list1.txt
done

# num_list.txtの中身を表示
cat num_list1.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# num_list.txtの先頭10行を表示
cat num_list1.txt | head -n 10

1
2
3
4
5
6
7
8
9
10

# 次の方法でも可能
head -n 10 num_list1.txt

1
2
3
4
5
6
7
8
9
10

末尾の表示(コマンド:tail)

# 1~50の数字をnum_list.txtに格納
for num in {1..50}
do
	echo "${num}" >> num_list2.txt
done

# num_list.txtの中身を表示
cat num_list2.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# num_list.txtの末尾10行を表示
cat num_list2.txt | tail -n 10

41
42
43
44
45
46
47
48
49
50

# 次の方法でも可能
tail -n 10 num_list2.txt

41
42
43
44
45
46
47
48
49
50

ソート処理(コマンド:sort)

# 1~10の数字をランダムにnum_list_random.txtに格納
for num in 1 8 2 5 6 7 3 0 4 9
do
	echo "${num}" >> num_list_random.txt
done

# num_list_random.txtの中身を表示
cat num_list_random.txt

1
8
2
5
6
7
3
0
4
9

# 数字でソートして表示
cat num_list_random.txt | sort

0
1
2
3
4
5
6
7
8
9

# 以下でもソート可能
sort num_list_random.txt

0
1
2
3
4
5
6
7
8
9

重複削除(コマンド:uniq)

# 1~3の数字を重複ありで、num_list_overlapping.txtに格納
for num in 1 2 3 2 1 3 1 3
do
	echo "${num}" >> num_list_overlapping.txt
done

# num_list_overlapping.txtの中身を表示
cat num_list_overlapping.txt

1
2
3
2
1
3
1
3

# 重複のない数字を表示
cat num_list_overlapping.txt | sort | uniq

1
2
3

# sortコマンドのオプション(-u)を使って、次のようにも可能
sort -u num_list_overlapping.txt

1
2
3

文字列の切り出し・抽出(コマンド:cut)

区切り文字を指定して抽出

# カンマ(,)区切りで表示
echo '1,2,3,4,5'

# カンマを区切り文字として、3文字目を抽出
## <a name='d:'></a>-d: 区切り文字指定
## <a name='f:'></a>-f: フィールドの指定
echo '1,2,3,4,5' | cut -d , -f 3

1,2,3,4,5
3

文字のインデックスを指定して抽出

# 1~5までの数字を表示
echo '12345'

# 先頭から3~5番目の文字を表示
## <a name='c:'></a>-c: 先頭からの文字数
echo '12345' | cut -c 3-5

12345
345

文字列の置換(コマンド:sed)

# 「Hello world!」という文字列を表示
echo 'Hello world!'

# 「world」を「Japan」に置換
echo 'Hello world!' | sed "s|world|Japan|g"

Hello world!
Hello Japan!

数字の連番(コマンド:seq)

# 1~10の数字を表示
seq 1 10

1
2
3
4
5
6
7
8
9
10

# 文字数(幅)を合わせて、1~10の数字を表示
# -w: 最大の文字数に合わせて0埋め
seq -w 1 10

01
02
03
04
05
06
07
08
09
10

コマンドのレファレンスマニュアルを表示(コマンド:man)

# lsのマニュアルを表示
man ls

LS(1) User Commands LS(1)

NAME
ls – list directory contents

SYNOPSIS
ls [OPTION]… [FILE]…

DESCRIPTION
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor –sort is speci‐
fied.

Mandatory arguments to long options are mandatory for short options
too.

-a, –all
do not ignore entries starting with .

-A, –almost-all
do not list implied . and ..

–author
with -l, print the author of each file

-b, –escape
print C-style escapes for nongraphic characters

–block-size=SIZE
scale sizes by SIZE before printing them; e.g., ‘–block-size=M’
prints sizes in units of 1,048,576 bytes; see SIZE format below

-B, –ignore-backups
do not list implied entries ending with ~

-c> with -lt: sort by, and show, ctime (time of last modification of
file status information); with -l: show ctime and sort by name;
otherwise: sort by ctime, newest first

-C> list entries by columns

–color[=WHEN]
colorize the output; WHEN can be ‘always’ (default if omitted),
‘auto’, or ‘never’; more info below

-d, –directory
list directories themselves, not their contents

-D, –dired
generate output designed for Emacs’ dired mode

-f> do not sort, enable -aU, disable -ls –color

-F, –classify
append indicator (one of */=>@|) to entries

–file-type
likewise, except do not append ‘*’

–format=WORD
across -x, commas -m, horizontal -x, long -l, single-column -1,
verbose -l, vertical -C

–full-time
like -l –time-style=full-iso

-g> like -l, but do not list owner

–group-directories-first
group directories before files;

can be augmented with a –sort option, but any use of
–sort=none (-U) disables grouping

-G, –no-group
in a long listing, don’t print group names

-h, –human-readable
with -l and/or -s, print human readable sizes (e.g., 1K 234M 2G)

–si likewise, but use powers of 1000 not 1024

-H, –dereference-command-line
follow symbolic links listed on the command line

–dereference-command-line-symlink-to-dir
follow each command line symbolic link

that points to a directory

–hide=PATTERN
do not list implied entries matching shell PATTERN (overridden
by -a or -A)

–hyperlink[=WHEN]
hyperlink file names; WHEN can be ‘always’ (default if omitted),
‘auto’, or ‘never’

–indicator-style=WORD
append indicator with style WORD to entry names: none (default),
slash (-p), file-type (–file-type), classify (-F)

-i, –inode
print the index number of each file

-I, –ignore=PATTERN
do not list implied entries matching shell PATTERN

-k, –kibibytes
default to 1024-byte blocks for disk usage

-l> use a long listing format

-L, –dereference
when showing file information for a symbolic link, show informa‐
tion for the file the link references rather than for the link
itself

-m> fill width with a comma separated list of entries

-n, –numeric-uid-gid
like -l, but list numeric user and group IDs

-N, –literal
print entry names without quoting

-o> like -l, but do not list group information

-p, –indicator-style=slash
append / indicator to directories

-q, –hide-control-chars
print ? instead of nongraphic characters

–show-control-chars
show nongraphic characters as-is (the default, unless program is
‘ls’ and output is a terminal)

-Q, –quote-name
enclose entry names in double quotes

–quoting-style=WORD
use quoting style WORD for entry names: literal, locale, shell,
shell-always, shell-escape, shell-escape-always, c, escape

-r, –reverse
reverse order while sorting

-R, –recursive
list subdirectories recursively

-s, –size
print the allocated size of each file, in blocks

-S> sort by file size, largest first

–sort=WORD
sort by WORD instead of name: none (-U), size (-S), time (-t),
version (-v), extension (-X)

–time=WORD
with -l, show time as WORD instead of default modification time:
atime or access or use (-u); ctime or status (-c); also use
specified time as sort key if –sort=time (newest first)

–time-style=STYLE
with -l, show times using style STYLE: full-iso, long-iso, iso,
locale, or +FORMAT; FORMAT is interpreted like in ‘date’; if
FORMAT is FORMAT1FORMAT2, then FORMAT1 applies to
non-recent files and FORMAT2 to recent files; if STYLE is pre‐
fixed with ‘posix-‘, STYLE takes effect only outside the POSIX
locale

-t> sort by modification time, newest first

-T, –tabsize=COLS
assume tab stops at each COLS instead of 8

-u> with -lt: sort by, and show, access time; with -l: show access
time and sort by name; otherwise: sort by access time, newest
first

-U> do not sort; list entries in directory order

-v> natural sort of (version) numbers within text

-w, –width=COLS
set output width to COLS. 0 means no limit

-x> list entries by lines instead of by columns

-X> sort alphabetically by entry extension

-Z, –context
print any security context of each file

-1> list one file per line. Avoid ‘\n’ with -q or -b

–help display this help and exit

–version
output version information and exit

The SIZE argument is an integer and optional unit (example: 10K is
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,…
(powers of 1000).

Using color to distinguish file types is disabled both by default and
with –color=never. With –color=auto, ls emits color codes only when
standard output is connected to a terminal. The LS_COLORS environment
variable can change the settings. Use the dircolors command to set it.

Exit status:
0> if OK,

1> if minor problems (e.g., cannot access subdirectory),

2> if serious trouble (e.g., cannot access command-line argument).

AUTHOR
Written by Richard M. Stallman and David MacKenzie.

REPORTING BUGS
GNU coreutils online help: http://www.gnu.org/software/coreutils/
Report ls translation bugs to http://translationproject.org/team/

COPYRIGHT
Copyright © 2017 Free Software Foundation, Inc. License GPLv3+: GNU
GPL version 3 or later http://gnu.org/licenses/gpl.html.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

SEE ALSO
Full documentation at: http://www.gnu.org/software/coreutils/ls
or available locally via: info ‘(coreutils) ls invocation’

GNU coreutils 8.28 January 2018 LS(1)

# cpのマニュアルを表示
man cp

CP(1) User Commands CP(1)

NAME
cp – copy files and directories

SYNOPSIS
cp [OPTION]… [-T] SOURCE DEST
cp [OPTION]… SOURCE… DIRECTORY
cp [OPTION]… -t DIRECTORY SOURCE…

DESCRIPTION
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options
too.

-a, –archive
same as -dR –preserve=all

–attributes-only
don’t copy the file data, just the attributes

–backup[=CONTROL]
make a backup of each existing destination file

-b> like –backup but does not accept an argument

–copy-contents
copy contents of special files when recursive

-d> same as –no-dereference –preserve=links

-f, –force
if an existing destination file cannot be opened, remove it and
try again (this option is ignored when the -n option is also
used)

-i, –interactive
prompt before overwrite (overrides a previous -n option)

-H> follow command-line symbolic links in SOURCE

-l, –link
hard link files instead of copying

-L, –dereference
always follow symbolic links in SOURCE

-n, –no-clobber
do not overwrite an existing file (overrides a previous -i
option)

-P, –no-dereference
never follow symbolic links in SOURCE

-p> same as –preserve=mode,ownership,timestamps

–preserve[=ATTR_LIST]
preserve the specified attributes (default: mode,ownership,time‐
stamps), if possible additional attributes: context, links,
xattr, all

–no-preserve=ATTR_LIST
don’t preserve the specified attributes

–parents
use full source file name under DIRECTORY

-R, -r, –recursive
copy directories recursively

–reflink[=WHEN]
control clone/CoW copies. See below

–remove-destination
remove each existing destination file before attempting to open
it (contrast with –force)

–sparse=WHEN
control creation of sparse files. See below

–strip-trailing-slashes
remove any trailing slashes from each SOURCE argument

-s, –symbolic-link
make symbolic links instead of copying

-S, –suffix=SUFFIX
override the usual backup suffix

-t, –target-directory=DIRECTORY
copy all SOURCE arguments into DIRECTORY

-T, –no-target-directory
treat DEST as a normal file

-u, –update
copy only when the SOURCE file is newer than the destination
file or when the destination file is missing

-v, –verbose
explain what is being done

-x, –one-file-system
stay on this file system

-Z> set SELinux security context of destination file to default type

–context[=CTX]
like -Z, or if CTX is specified then set the SELinux or SMACK
security context to CTX

–help display this help and exit

–version
output version information and exit

By default, sparse SOURCE files are detected by a crude heuristic and
the corresponding DEST file is made sparse as well. That is the behav‐
ior selected by –sparse=auto. Specify –sparse=always to create a
sparse DEST file whenever the SOURCE file contains a long enough
sequence of zero bytes. Use –sparse=never to inhibit creation of
sparse files.

When –reflink[=always] is specified, perform a lightweight copy, where
the data blocks are copied only when modified. If this is not possible
the copy fails, or if –reflink=auto is specified, fall back to a stan‐
dard copy.

The backup suffix is ‘~’, unless set with –suffix or SIM‐
PLE_BACKUP_SUFFIX. The version control method may be selected via the
–backup option or through the VERSION_CONTROL environment variable.
Here are the values:

none, off
never make backups (even if –backup is given)

numbered, t
make numbered backups

existing, nil
numbered if numbered backups exist, simple otherwise

simple, never
always make simple backups

As a special case, cp makes a backup of SOURCE when the force and
backup options are given and SOURCE and DEST are the same name for an
existing, regular file.

AUTHOR
Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering.

REPORTING BUGS
GNU coreutils online help: http://www.gnu.org/software/coreutils/
Report cp translation bugs to http://translationproject.org/team/

COPYRIGHT
Copyright © 2017 Free Software Foundation, Inc. License GPLv3+: GNU
GPL version 3 or later http://gnu.org/licenses/gpl.html.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

SEE ALSO
Full documentation at: http://www.gnu.org/software/coreutils/cp
or available locally via: info ‘(coreutils) cp invocation’

GNU coreutils 8.28> > January 2018> > > > CP(1)

ワイルドカード [ * ] (コマンド:*)

# このチュートリアルで生成したファイルを一括削除
rm -r error_log.txt clone.txt file* num_list* output_* *Dir

Print Friendly, PDF & Email

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください