Skip to content

Instantly share code, notes, and snippets.

@Bilal2453
Created February 19, 2023 20:14
Show Gist options
  • Save Bilal2453/01502da0c53eb2c6d23c20865c979d87 to your computer and use it in GitHub Desktop.
Save Bilal2453/01502da0c53eb2c6d23c20865c979d87 to your computer and use it in GitHub Desktop.
A simple automation I use to real-quick switch between my Nvidia dGPU and my iGPU on Fedora. This is NOT how you are supposed to do it, rather create a boot entry menu that sets the said cmdlines!
#!/bin/lua
local GRUB_CONFIG_PATH = "/etc/default/grub"
local GRUB_MKCONFIG = "sudo grub2-mkconfig -o /boot/grub2/grub.cfg"
local RD_BLACKLIST = "rd.driver.blacklist=nouveau"
local MODPROBE_BLACKLIST = "modprobe.blacklist=nouveau"
local DRM_MODSET = "nvidia%-drm.modeset=1"
local function enable(current_val)
local new_str = current_val
local rd_blacklist = current_val:match(RD_BLACKLIST)
local modprobe_blacklist = current_val:match(MODPROBE_BLACKLIST)
local drm_modset = current_val:match(DRM_MODSET)
if not rd_blacklist then
new_str = RD_BLACKLIST .. ' ' .. new_str
end
if not modprobe_blacklist then
new_str = MODPROBE_BLACKLIST .. ' ' .. new_str
end
if not drm_modset then
new_str = DRM_MODSET:gsub('%%', '') .. ' ' .. new_str
end
return new_str
end
local function disable(current_val)
return current_val:gsub(RD_BLACKLIST, "")
:gsub(MODPROBE_BLACKLIST, "")
:gsub(DRM_MODSET, "")
end
local function get_grub_config()
local fd = assert(io.open(GRUB_CONFIG_PATH, "r"))
local str = assert(fd:read('*a'))
fd:close()
return str
end
local function get_cmdline(configs)
local val = assert(configs:match('GRUB_CMDLINE_LINUX="(.-)"'), "Could not parse the GRUB config file for GRUB_CMDLINE_LINUX")
return val
end
local function write_grub_config(configs, new_cmdline)
configs = configs:gsub('GRUB_CMDLINE_LINUX=".-"', 'GRUB_CMDLINE_LINUX="' .. new_cmdline .. '"')
local fd = assert(io.open(GRUB_CONFIG_PATH, "w"))
assert(fd:write(configs))
fd:close()
end
local grub_config = get_grub_config()
local cmdline = get_cmdline(grub_config)
local new_cmdline
if arg[1] == "enable" or arg[2] == "enable" then
new_cmdline = enable(cmdline)
elseif arg[1] == "disable" or arg[2] == "disable" then
new_cmdline = disable(cmdline)
else
print "Usage: nvidiactl 'enable'|'disable'"
os.exit(0)
end
print("Changing GRUB_CMDLINE_LINUX to \n" .. new_cmdline)
write_grub_config(grub_config, new_cmdline)
print("\nChanges Written.")
print("Regenerating GRUB configs: " .. GRUB_MKCONFIG .. '\n\n')
os.execute(GRUB_MKCONFIG)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment