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?

ShellScriptの引数もLinuxコマンドのオプションみたいに指定できるようにしたい

Posted at

背景・目的

  • 作業効率アップのためにデータ集計スクリプトを作成することにした
  • 引数が多くなりそうだったので、どの引数かわかりやすくするため、引数をLinuxコマンドのオプション風に指定できるようにしたかった

コード

#!/bin/bash

for arg in "$@"; do
  case "${arg}" in
    --start-date=*) START_DATE="${arg#*=}" ;;
    --end-date=*) END_DATE="${arg#*=}" ;;
    --error-str=*) ERROR_STR="${arg#*=}" ;;
    --info-str=*) INFO_STR="${arg#*=}" ;;
    --target-file*) TARGET_FILE="${arg#*=}" ;;
    *) echo 'オプション不正' ;;
  esac
done

実行

$ sample.sh --start-date="2025-01-01 00:00:00" --end-date="2025-01-01 23:59:59" --error-str="exampleError" --info-str="exampleSuccess" --target-file="example.log"

ワンポイント解説

  • 該当する引数の値を変数に定義している
  • ${arg#*=}はイコールで繋がっている文字列の右辺だけを取得する

補足

-vや--versionのように複数種類のオプション名に対応したい場合はパイプで繋げる

for arg in "$@"; do
  case "${arg}" in
    -V=*|--version=*) VERSION="${arg#*=}" ;;
    *) echo 'オプション不正' ;;
  esac
done
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?