はじめに
Ubuntuで標準のBashは、自動補完機能があまり強力ではありません。
oh-my-zshは、見た目の良さだけでなく、自動補完や過去に入力したコマンドのサジェスト機能が非常に優れており、個人的には満足して利用しています。
しかし、開発環境がコンテナ、特にDevcontainerの場合、多くの場合シェルがBashに戻ってしまいます。
今回は、リポジトリのDockerfileやdevcontainer.jsonを変更することなく、Devcontainerのシェルをoh-my-zshにする方法を試みました。この目的を達成するために、dotfilesを活用しています。
dotfilesについては、こちらの素晴らしい解説をご参照ください。
dotfiles用のRepository
お試しとして、oh-my-zshをdotfilesで利用するためのリポジトリを、こちら に作成しました。
リポジトリの内容は以下の通りです。
zsh, oh-my-zsh, プラグインをインストール
sudo apt-get install -y zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
sudo apt-get install -y bat
ZSH_CUSTOM="${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}"
mkdir -p "$ZSH_CUSTOM/plugins"
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-"$HOME/.oh-my-zsh/custom"}/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-syntax-highlighting ${ZSH_CUSTOM:-"$HOME/.oh-my-zsh/custom"}/plugins/zsh-syntax-highlighting
git clone https://github.com/fdellwing/zsh-bat "$ZSH_CUSTOM/plugins/zsh-bat"
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git "${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k"
oh-my-zshのプラグインについてはこちらを参照ください。
zshrcとpowerlevel10kの.p10k.zshをコピー
cp $script_dir/dotfiles/.zshrc ~/.zshrc
cp $script_dir/dotfiles/.p10k.zsh ~/.p10k.zsh
.zshrcにはプラグインの記載が必要です。プラグイン追加のコマンドに加えてここもお気に入りの設定にしてもらえればと思います。
ZSH_THEME="powerlevel10k/powerlevel10k"
plugins=(git zsh-autosuggestions zsh-syntax-highlighting docker zsh-bat)
bashrcの設定をコピー
Dockerfileで.bashrcに環境変数が記述されている場合、Zshではそのままでは動作しません。この問題に対処するため、.bashrcから.zshrcに必要な行をコピーします。
if [ -f ~/.bashrc ]; then
echo "⚙️ Converting .bashrc environment variables for zsh..."
echo -e "\n# Environment variables from .bashrc\n$(grep '^export ' ~/.bashrc | grep -v 'shopt\|function')\n" >> ~/.zshrc
echo -e "\n# Aliases from .bashrc\n$(grep '^alias ' ~/.bashrc)\n" >> ~/.zshrc
echo -e "\n# Source commands from .bashrc\n$(grep '^source ' ~/.bashrc)\n" >> ~/.zshrc
fi
VScodeの設定
VS codeのユーザー設定のsettings.json
に、dotfilesとデフォルトのシェルを設定します。
Ctrl + Shift + p
で、「Open User Settings (JSON)」を選ぶとsettings.json
が開くので、以下のように設定します。
"dotfiles.repository": "https://github.com/AkihiroUeda35/zsh-dotfiles.git", // URL of this dotfiles repository
"dotfiles.targetPath": "~/dotfiles", //repository will be cloned to this path
"dotfiles.installCommand": "install.sh", // command to run after cloning the repository
"terminal.integrated.defaultProfile.linux": "zsh", // set zsh as default shell ( if not found, bash will be used)
これでRepositoryをDevcontainerで開くと、Terminalがzshに変わります!!
まとめ
dotfilesを活用することで、Devcontainerでもoh-my-zshを利用できるようになりました。
Devcontainerで開発を行っていてoh-my-zshを使いたいものの、Dockerfileやdevcontainer.jsonを変更できないといった状況の方は、ぜひこの方法を試してみてはいかがでしょうか。