LoginSignup
3
2

More than 5 years have passed since last update.

Shellの基本を学ぶ(9)スクリプトを実行する様々な方法

Posted at

ファイルからの実行

hash-bang を使った実行

Bashのサブプロセスがスタートする。ファイルの実効権限が必要。

hash-bang のない場合

下記の通り。実行権限は必要ない。

bash yourscript

bash -x yourscript でデバッグモードになる。

$bash -x mvext jpg txt
+ [[ 2 -ne 2 ]]
+ for f in *"$1"
+ mv -- -a.jpg -a.txt
+ for f in *"$1"
+ mv -- a.jpg a.txt
+ for f in *"$1"
+ mv -- b.jpg b.txt
+ for f in *"$1"
+ mv -- c.jpg c.txt

現在のシェルのプロセスでファイルを実行

source もしくは、. シノニム。

$ source yourscript
$ . yourscript

.bashrc で使われている方法。

バックグラウンドとnohup

& バックグラウンド実行

yourscript & でよい。現在のインタラクティブセッションから切り離される。標準入力から読もうとすると止まってしまう。ターミナルが終了しても、バックグラウン実行したい場合は、nohup yourscript &

低いプライオリティで実行したい場合

nice

nohup nice yourscript &

サンプル

stillhere

#!/bin/bash

declare -i i=0
while true; do 
  echo "still here $((++i))"
  sleep 1
done

これを実行して、ターミナルを閉じても、ちゃんと動作する。

TERM 1

nohup stillhere > stillhere.log &
[kill this terminal]

TERM 2

動き続ける。

$tail -f still.log
still here 5
still here 6
still here 7
still here 8
still here 9
still here 10
still here 11
still here 12
still here 13
still here 14
still here 15
still here 16
still here 17
still here 18
still here 19
still here 20
still here 21
still here 22
still here 23
still here 24
still here 25
still here 26
still here 27
still here 28
still here 29
still here 30
still here 31

exec

I/O をリダイレクト出来るので、ログなどに便利。exec > logfile 2> error.log

次のコードで結果が自動でlogfile にはかれる。

stillhere

#!/bin/bash

declare -i i=0

if [[ $1 == "-l" ]]; then
  exec >logfile
fi
declare -i i=0
while true; do 
  echo "still here $((++i))"
  sleep 1
done

クーロン

At

特定の時間にスクリプトを動かす。

at -f yourscript noon tomorrow

Cron

Mac はlaunchd
Ubuntu は  Upstart

set と shopt

Bash の振る舞いをカスタマイズする。

set

-x

全ての実行されたコマンドを引数付きで表示する。

-u

初期化していない変数や、exits があるとエラーをはく

-n

コマンドを読むが実行しない

-v

全てのコマンドを読んで表示する。-n と合わせると、コマンドを実行せず表示出来る。

-e

コマンドが失敗したらexit する(ただし、if, while, until || && 以外)

shopt

-sでオプションを設定し、-uで設定の解除

  • shopt -s nocaseglob パス名のケース(大文字小文字)を無視する
  • shopt -s extglob 拡張パターンマッチングを使用可能する
  • shopt -s dotglob 隠しファイル(.) を使用可能にする。
  • set -o noclobber リダイレクトでファイルを上書きしない
3
2
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
3
2