😊

【備忘録】shellscriptよく使うもの

2022/01/18に公開

変数をexportしてshellscriptのその後のコマンドで使用する

ワンライナーで複数のコマンドを実行するときに先頭で変数をexportしておく。なぜか、&&ではだめではまった。

export containername=hasura; aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin dkr.ecr.ap-northeast-1.amazonaws.com && docker build -f Dockerfile.hasura -t ${container_name} . && docker tag ${container_name}:latest dkr.ecr.ap-northeast-1.amazonaws.com/${container_name}:latest && docker push dkr.ecr.ap-northeast-1.amazonaws.com/${container_name}:latest

一行で複数の命令を実行する方法

dockerfileのrunコマンドで重宝する書き方です。

RUN set -eux; \
      {\
       sed -i -e "s/@app_password/${app_password}/g" /docker-entrypoint-initdb.d/*.sh; \
      }

heredocの結果を処理したら変数に入れる方法

heredocは標準入力に該当するのでこのような書き方になります。

command=`cat << EOS | fzf
fcd
fdb
fdbcsv
fmake
fmakel
ftmux
fproject
fcmd
EOS

echo $command

スペース区切りの文字列のn番目以降を取得する方法

echo "hello world heyhey" | cut -d ' ' -f 2-
>> world heyhey

retry timeoutをかんたんに実装する方法

RETRIES=10
# 2>&1 の&はマージを意味していて、2>1とした場合には、標準エラー出力を1というファイルに書くという意味になる。
# 2>&1 とすることで、標準エラー出力と標準出力をまとめるという意味になる。
# echo "hello" > sample.txt 2>&1  // これは、sample.txtにどちらであろうと書き込むという意味。
until psql postgres://postgres:postgrespassword@localhost:5432/dvdrental -c "select 1" > /dev/null 2>&1 || [ $RETRIES -eq 0 ]; do
  echo "Waiting postgres server $((RETRIES--)) remaining attempts..."
  sleep 20
done
if [ "$RETRIES" = '0' ]; then
  echo "time out"
  exit 1
else
  echo "bootstrap finished"
fi

Discussion

ログインするとコメントできます