Modify .desktop Files with a Bash Script

If you're looking to modify .desktop files on your Linux system, here's a handy Bash script to help you automate the process. This script specifically updates the Exec line for Google Chrome to include additional flags for enabling the Ozone platform and touchpad overscroll history navigation.

The Script


#!/bin/bash

modify_desktop_entry() {
    local file="$1"
    local tmpfile=$(mktemp)
    local pattern='^Exec=/opt/google/chrome/google-chrome'

    if ! [[ -f "$file" ]]; then
        printf "File not found: %s\n" "$file" >&2
        return 1
    fi

    while IFS= read -r line; do
        if [[ $line =~ $pattern ]]; then
            printf "%s --enable-features=UseOzonePlatform,TouchpadOverscrollHistoryNavigation --ozone-platform=wayland\n" "$line" >> "$tmpfile"
        else
            printf "%s\n" "$line" >> "$tmpfile"
        fi
    done < "$file"

    mv "$tmpfile" "$file"
}

main() {
    local files=("$@")

    if [[ ${#files[@]} -eq 0 ]]; then
        printf "Usage: %s   ...\n" "${0##*/}" >&2
        return 1
    fi

    for file in "${files[@]}"; do
        if ! modify_desktop_entry "$file"; then
            printf "Failed to modify: %s\n" "$file" >&2
            continue
        fi
    done
}

main "$@"
    

Explanation

modify_desktop_entry: This function takes a file path as an argument and modifies it. It checks if the file exists and reads it line by line.

  • If a line matches the pattern for the Chrome executable, it appends the desired flags to the Exec line.
  • A temporary file is used to store the modified content, which is then moved to replace the original file.

main: This function handles the input arguments (which should be file paths). It checks