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?

[Shell]指定のプロパティファイルから特定キーの値を取得

Posted at

コマンド実行

test.properties
SEND_URL=http://localhost:8080/keys
TIMEOUT=1000
$ grep "SEND_URL" test.properties | cut -d'=' -f2

http://localhost:8080/keys

shellファイル化

test.sh
#!/bin/bash

# プロパティファイル
PROPERTY_FILE="test.properties"

# キーを指定
KEY="SEND_URL"

# 値を取得
VALUE=$(grep "^$KEY=" $PROPERTY_FILE | cut -d'=' -f2)

# 値を表示
echo "$VALUE"
$ chmod 755 test.sh
$ ./test.sh

http://localhost:8080/keys

外部ファイルと引数を組み合わせる

config.env
# 外部設定ファイル (config.env)
PROPERTY_FILE="/home/sano2/dkwork3/test.properties"
TARGET_KEY="SEND_URL"
test2.sh
#!/bin/bash

# 外部設定ファイルの読み込み
CONFIG_FILE="config.env"
if [ -f "$CONFIG_FILE" ]; then
  source "$CONFIG_FILE"
fi

# 引数で上書き
PROPERTY_FILE=${1:-$PROPERTY_FILE}
TARGET_KEY=${2:-$TARGET_KEY}

# 引数またはデフォルト値の確認
if [ -z "$PROPERTY_FILE" ] || [ -z "$TARGET_KEY" ]; then
  echo "Usage: $0 [property_file] [key]"
  exit 1
fi

# プロパティファイルからキーの値を取得
VALUE=$(grep "^$TARGET_KEY=" "$PROPERTY_FILE" | cut -d'=' -f2)
if [ -z "$VALUE" ]; then
  echo "Key $TARGET_KEY not found in $PROPERTY_FILE"
  exit 1
fi

# 結果を表示
echo "$VALUE"
$ chmod 755 test2.sh

# プロパティパス+ファイル名とプロパティのキーはconfig.envのデフォルト値を使用
$ ./test2.sh

http://localhost:8080/keys

# プロパティパス+ファイル名はconfig.envのデフォルト値、プロパティのキーは引数で指定されたものを使用
$ ./test2.sh "" "TIIMEOUT"

1000
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?