본문 바로가기

Dev/OS

[UBUNTU] 파일에서 특정 텍스트를 치환해주는 Shell Script

쉘 스크립트를 작성하다보면, config 파일에 저장되는 민감정보들이 엄한데에 저장되지 않도록 스크립트 구동시에 관련 텍스트를 치환되도록 하는 기능이 필요하다. 구글링을 통해 알아놓고 요긴하게 자주 써먹는 코드다.

UBUNTU 18.04 에서 동작하는 것을 확인했다. 다른 OS 계열 (macOS)에서는 아래의 코드를 돌리기 위해 추가 설치해야 하는 것들이 있을수 있고 코드도 고쳐야 한다. sed의 경우만 해도 리눅스에서는 gnu 라이센스의 sed가 돌아가지만 unix계열인 macOS에서는 bsd 라이센스의 sed가 탑재되어 있으며 이 둘의 옵션이 다르다.

## Copies configuration template to the destination as the specified USER
### Looks up for overrides in ${USERCONF_TEMPLATES_DIR} before using the defaults from ${SYSCONF_TEMPLATES_DIR}
# $1: copy-as user
# $2: source file
install_template() {
  local SRC=${1}
  local DEST=${2}

  cp ${RUNTIME_DIR}/${SRC} ${DEST}
}

## Replace placeholders with values
# $1: file with placeholders to replace
# $x: placeholders to replace
update_template() {
  local FILE=${1?missing argument}
  shift

  [[ ! -f ${FILE} ]] && return 1

  local VARIABLES=($@)
  local USR=$(stat -c %U ${FILE})
  local tmp_file=$(mktemp)
  cp -a "${FILE}" ${tmp_file}

  local variable
  for variable in ${VARIABLES[@]}; do
    # Keep the compatibilty: {{VAR}} => ${VAR}
    sed -ri "s/[{]{2}$variable[}]{2}/\${$variable}/g" ${tmp_file}
  done

  # Replace placeholders
  (
    export ${VARIABLES[@]}
    local IFS=":"; sudo -HEu ${USR} envsubst "${VARIABLES[*]/#/$}" < ${tmp_file} > ${FILE}
  )
  rm -f ${tmp_file}
}

  install_template 'config/application.rb' ${APPLICATION_CONFIG}

  update_template ${DATABASE_CONFIG} \
    DB_NAME \
    DB_HOST \
    DB_PORT \
    DB_USER \
    DB_PASS