script header

一般のシェルのヘッダーでよく使う処理

やりたいこと

  1. ./test.shで実行された場合にもシェルのフルパスを取得したい。
  2. 引数のチェックをしたい。
  3. ユーザーのチェックをしたい。

#!/bin/bash
#######################################
# name test.sh
#######################################
# type 1
SCRIPT_DIR=$(cd $(dirname $0); pwd)
SCRIPT_BASE=$(basename $0)
echo "Base1=${SCRIPT_BASE}"
echo "Dir1=${SCRIPT_DIR}"

# type 2 high performance
SCRIPT_DIR=$(cd ${0%/*}; pwd)
SCRIPT_BASE=${0##*/}
echo "Base2=${SCRIPT_BASE}"
echo "Dir2=${SCRIPT_DIR}"

if [[ $# -ne 1 ]]; then
    echo "This shell will ..."
    echo "syntax ${SCRIPT_BASE} parameter1"
    echo "e.g. ${SCRIPT_BASE} parameter1"
    echo
    exit 9
fi

if [[ $(whoami) != 'user1' && $(whoami) != 'root' ]]; then
    echo "please login as user1 or root!"
    exit 8
fi
# timestamp付きのログファイル名
LOG_FILE=logfile_$(date "+%Y%m%d%H%M%S").log

exit 0

実行例

# ./test.sh
Base1=test.sh
Dir1=/Users/ tester/script
Base2=test.sh
Dir2=/Users/tester/script
This shell will ...
syntax test.sh parameter1
e.g. test.sh parameter1

コメント

人気の投稿