automate/grub-commandline_mod.sh

84 lines
1.8 KiB
Bash
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# --- DEFAULTS ---
FILE="/etc/default/grub"
DRY_RUN=false
NEW_SETTING=""
# --- HELP FUNCTION ---
usage() {
echo "Usage: sudo $0 [OPTION] \"setting=value\""
echo "Example: sudo $0 \"consoleblank=3\""
echo ""
echo "Options:"
echo " -d, --dry-run Show changes without applying them"
echo " -h, --help Display this help message"
exit 1
}
# --- ARGUMENT PARSING ---
while [[ $# -gt 0 ]]; do
case $1 in
-d | --dry-run)
DRY_RUN=true
shift
;;
-h | --help)
usage
;;
*)
NEW_SETTING="$1"
shift
;;
esac
done
# Check if a setting was actually provided
if [[ -z "$NEW_SETTING" ]]; then
echo "❌ Error: No GRUB setting provided."
usage
fi
# --- LOGIC ---
apply_grub_change() {
local TARGET="$1"
# Regex: Appends TARGET inside the quotes of GRUB_CMDLINE_LINUX_DEFAULT
local SED_LOGIC="/^GRUB_CMDLINE_LINUX_DEFAULT=/ s/\"\([^\"]*\)\"/\"\1 $TARGET\"/; s/ */ /g; s/ $TARGET\"/$TARGET\"/"
# 1. PRE-CHECK
if grep -q "$TARGET" "$FILE"; then
echo " SKIP: '$TARGET' already exists in $FILE."
return 0
fi
# 2. EXECUTION
if [ "$DRY_RUN" = true ]; then
echo "🔍 DRY RUN: Simulating '$TARGET' addition..."
grep "^GRUB_CMDLINE_LINUX_DEFAULT=" "$FILE" | sed "$SED_LOGIC"
else
# Ensure script is run as root for actual changes
if [[ $EUID -ne 0 ]]; then
echo "❌ Error: This script must be run with sudo to apply changes."
exit 1
fi
echo "💾 Backing up to $FILE.bak..."
cp "$FILE" "$FILE.bak"
echo "🔧 Applying '$TARGET' to $FILE..."
sed -i "$SED_LOGIC" "$FILE"
# 3. VERIFICATION & UPDATE
if grep -q "$TARGET" "$FILE"; then
echo "✅ SUCCESS: Updating bootloader..."
update-grub
else
echo "❌ ERROR: Failed to apply changes."
exit 1
fi
fi
}
# --- EXECUTE ---
apply_grub_change "$NEW_SETTING"