Bash
根據 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。
這是一種方法:
#!/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"