Fragments of verbose memory

冗長な記憶の断片 - Web技術のメモをほぼ毎日更新(準備中)

Jan 17, 2021 - 日記

サーバの作業環境を初期設定をするシェルスクリプト

新しい作業用サーバを建てたときに作業環境を真っ先に設置するためのスクリプトにmovein.shと言う便利なのがあります。

オリジナルのスクリプトがgistにあったので掲載します。

#!/bin/sh
# movein.sh - shamelessly stolen from O'Reilly's excellend "Linux Server Hacks"
# http://oreilly.com/pub/h/72
# Version 0.2 - Added some comments and error checking
if [ -z "$1" ]; then
echo "Usage: `basename $0` hostname"
exit
fi
if [ ! -d ~/.skel ]; then
echo "No ~/.skel directory was found. Please create it and add symlinks (or copies) of any files you want to be included."
exit 1
fi
# Here's the magic, this tars everything in ~/.skel up and pushes it out to the remote machine.
# Be careful to make sure there's nothing in ~/.skel that you don't want on the remote host!
cd ~/.skel
tar zhcf - . | ssh $1 "tar zpvxf -"
view raw movein.sh hosted with ❤ by GitHub

元ネタはO’ReillyのLinux Server Hacks

~/.skelに設定ファイルを用意しておいて、movein.sh SSHユーザ@SSHサーバを実行すれば接続先にコピーしてもらえると言うもの。~/.skelは、シンボリックリンクでも実体に変換されるので今使っている.zshrcとかをメンテナンスフリーでコピーできます。

ただ問答無用に上書きされてしまうので、rsyncつかって確認を出すように書き換えたのが以下のスクリプトです。

#!/bin/sh
commands='scp grep rsync diff mktemp'
for c in $commands; do
hash $c || { echo "install $c"; exit 255; }
done
if [ -z "$1" ]; then
echo "Usage: $(basename $0) hostname [go|diff]"
exit
fi
if [ ! -d ~/.skel ]; then
echo "No ~/.skel directory was found. Please create it and add symlinks (or copies) of any files you want to be included."
exit 1
fi
hostname=$1
command=$2
src=~/.skel/
dest=${hostname}:./
rsync_options="-rzPc --copy-links --executability --exclude .git"
case $command in
go)
rsync --progress $rsync_options $src $dest
;;
diff)
files=`rsync $rsync_options --dry-run $src $dest |grep -v "/$"`
for file in $files;
do
if [ -r $file ]; then
tempfile=$(mktemp)
touch ${tempfile}
scp ${dest}/${file} ${tempfile} 2>/dev/null
diff -uN ${tempfile} ${file}
rm ${tempfile}
fi
done
;;
*)
rsync $rsync_options --dry-run $src $dest |grep -v "/$"
while true; do
read -p "Do you wish to overwrite? [Y] " yn
case $yn in
[Yy]* ) rsync --progress $rsync_options $src $dest; break;;
* ) exit;;
esac
done
;;
esac
view raw movein hosted with ❤ by GitHub

使い方はオリジナルとほぼ同じ、違うのはDo you wish to overwrite? [Y] と聞かれたら差分確認してY押すだけです。