jasonwryan.com

Miscellaneous ephemera…

Script to Edit Config Files

image

Even with bash completion, endlessly typing and tabbing through the directory tree to make a simple change to a config file quickly becomes tedious, so I concocted this script to make it somewhat more straightforward.

xdg.sh
1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
dir=$XDG_CONFIG_HOME/$1
if [ -d "$dir" ]; then 
    for f in $dir/* ; do
    file=${f##*/}
        case $file in
        conf | config | *.cfg | *rc)  $EDITOR "$f" ;;
        *)  :  ;;
        esac
    done
fi

A relatively simple script, with a nice feature or two, it does a couple of things. First, it tests that the directory actually exists:

1
    if [ -d "$dir" ]

and then loops through all of the files in the directory using a glob and checks for a pattern match.

In order for the case statement to work, however, the directory path has to be stripped from the file name.

Rather than run another process with basename, I used parameter expansion to remove the substring:

1
    file=${f##*/}

which turns, for example, $XDG_CONGIG_HOME/newsbeuter/conf into a simple conf. This can then be evaluated for a match with the file names in the case statement and passed to the $EDITOR.

If no match is found, nothing (:) is done.

Now, it is simply a matter of entering xdg vimprobable and $XDG_CONFIG_HOME/vimprobable/vimprobablerc is opened in Vim.

Updated 19/10/11

After using this script for a while it became clear to me that it has a significant drawback: too many applications place their config files in directories other than $XDG_CONFIG_HOME. So, with some help, I updated the script. It now covers all of the directories where you are likely to find dotfiles.

xdg.sh v2
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
dirs=($HOME/.$1* $HOME/.$1/ $XDG_CONFIG_HOME/$1/)
IFS=$'\n'
read -r -d '' -a files < \
    <(find "${dirs[@]}" -type f \( \
           -name "*.conf" \
        -o -name "conf" \
        -o -name "config" \
        -o -name "*rc" \
        -o -name "*.cfg" \) 2>/dev/null)

(( ${#files[*]} )) && "$EDITOR" "${files}"

If you would prefer a more portable version—which still relies on GNU find—then you could simplify it like so:

xdg.sh v3
1
2
3
4
5
6
7
8
9
10
#!/bin/sh
dirs=($HOME/.$1* $HOME/.$1/ $XDG_CONFIG_HOME/$1/)

find "${dirs[@]}" -type f \( \
       -name "*.conf" \
    -o -name "conf" \
    -o -name "config" \
    -o -name "*rc" \
    -o -name "*.cfg" \) \
    -exec "$EDITOR" {} +

Comments