sudo アクセスに基づくスクリプトでの重複コードの防止

sudo アクセスに基づくスクリプトでの重複コードの防止

ここで重複コードを減らす方法はありますか?

if have_sudo_access; then
  echo "Installing system wide"
  FONTS_PATH="/usr/share/fonts/.local/share/fonts/"
  sudo mkdir -p "$FONTS_PATH"
  SauceCodePro="https://github.com/ryanoasis/nerd-fonts/blob/master/patched-fonts/SourceCodePro"
  sudo curl -L -o "$FONTS_PATH/Sauce Code Pro Nerd Font Regular.ttf" "$SauceCodePro/Regular/complete/Sauce%20Code%20Pro%20Nerd%20Font%20Complete.ttf"
  sudo curl -L -o "$FONTS_PATH/Sauce Code Pro Nerd Font Bold.ttf" "$SauceCodePro/Bold/complete/Sauce%20Code%20Pro%20Bold%20Nerd%20Font%20Complete.ttf"
  sudo curl -L -o "$FONTS_PATH/Sauce Code Pro Nerd Font Italic.ttf" "$SauceCodePro/Italic/complete/Sauce%20Code%20Pro%20Italic%20Nerd%20Font%20Complete.ttf"
else
  echo "Installing font for local user"
  FONTS_PATH="$HOME/.local/share/fonts/"
  mkdir -p "$FONTS_PATH"
  SauceCodePro="https://github.com/ryanoasis/nerd-fonts/blob/master/patched-fonts/SourceCodePro"
  curl -L -o "$FONTS_PATH/Sauce Code Pro Nerd Font Regular.ttf" "$SauceCodePro/Regular/complete/Sauce%20Code%20Pro%20Nerd%20Font%20Complete.ttf"
  curl -L -o "$FONTS_PATH/Sauce Code Pro Nerd Font Bold.ttf" "$SauceCodePro/Bold/complete/Sauce%20Code%20Pro%20Bold%20Nerd%20Font%20Complete.ttf"
  curl -L -o "$FONTS_PATH/Sauce Code Pro Nerd Font Italic.ttf" "$SauceCodePro/Italic/complete/Sauce%20Code%20Pro%20Italic%20Nerd%20Font%20Complete.ttf"
fi

私は次のことを考えてみました。

if have_sudo_access; then
  alias mysudo = "sudo "
else
  alias mysudo = ""
fi

その後、sudoが必要なすべてのコマンドにmysudoを使用します。

ベストアンサー1

1つの方法は次のとおりです。

#!/bin/bash

## make a temp dir
tmpDir=$(mktemp -d)

## Download the files to it
SauceCodePro="https://github.com/ryanoasis/nerd-fonts/blob/master/patched-fonts/SourceCodePro"
curl -L -o "$tmpDir/Sauce Code Pro Nerd Font Regular.ttf" "$SauceCodePro/Regular/complete/Sauce%20Code%20Pro%20Nerd%20Font%20Complete.ttf"
curl -L -o "$tmpDir/Sauce Code Pro Nerd Font Bold.ttf"    "$SauceCodePro/Bold/complete/Sauce%20Code%20Pro%20Bold%20Nerd%20Font%20Complete.ttf"
curl -L -o "$tmpDir/Sauce Code Pro Nerd Font Italic.ttf"  "$SauceCodePro/Italic/complete/Sauce%20Code%20Pro%20Italic%20Nerd%20Font%20Complete.ttf"

## Check for sudo access using whatever "have_sudo_access" is supposed to be
if have_sudo_access; then
  echo "Installing system wide"
  sudo mkdir -p "/usr/share/fonts/.local/share/fonts/"
  sudo mv "$tmpDir"/* "/usr/share/fonts/.local/share/fonts/"
else
  echo "Installing font for local user"
  mkdir -p "$HOME/.local/share/fonts/"
  mv "$tmpDir"/* "$HOME/.local/share/fonts/"
fi

## delete the now empty tmp dir
rmdir "$tmpDir"

おすすめ記事