Closed13

学習記録#24 250630

ろみぃ(konatsu)ろみぃ(konatsu)

シェルスクリプトの条件分岐

if 条件分
then
    実行文1
else
    実行文2
fi

ifとfiで括るの面白い

ろみぃ(konatsu)ろみぃ(konatsu)
# ls
iftest.sh  iftest2.sh  testscript
# cat iftest.sh
if test -f testscript
then
	source ./testscript
else
	echo "testscript file not exist."
fi

# cat iftest2.sh
if [ -f testscript2 ] ; then
	. ./testscript2
else echo "testscript2 file not exist."
fi
# bash iftest.sh
/theodore/if_test
# bash iftest2.sh
testscript2 file not exist.
ろみぃ(konatsu)ろみぃ(konatsu)

シェルスクリプトは、シェルの種類によって異なる。

bash用なら、スクリプトの先頭に

#!/bin/bash

のような記述が必要。

これを書くと、ユーザーの使っているシェルに関わらず、スクリプトは必ずbashで実行されるようになる

ろみぃ(konatsu)ろみぃ(konatsu)

自分だけでなくシステム内全てのユーザーが利用できるようにするには、①一般ユーザーのPATH変数に含まれているディレクトリに実行したいシェルスクリプトを配置し、②適切なアクセス権を設定する必要がある


配置するディレクトリは、/usr/local/binや/usr/local/sbinがよく使われる。
以下のように配置する。

$ sudo cp testscript.sh /usr/local/bin


シェルスクリプトのパーミッションは、その他ユーザーが読み取り・実行できるアクセス権に設定しておく

$ sudo chmod o+rx /usr/local/bin/testscript.sh
ろみぃ(konatsu)ろみぃ(konatsu)

bashの-vオプションを使うと、シェルスクリプト内で実行されるコマンドが標準エラー出力に出力される
→どのようなコマンドが実行されるか、実行結果とともに確認できる
dry run的なやつかな?

このスクラップは2ヶ月前にクローズされました