The Ops Community

Joseph D. Marhee
Joseph D. Marhee

Posted on

Coverting Bash Profile to Fish

I recently decided to try the fish shell, and decided, armed with a cheat sheet, to try to convert much of my bash profile. It's pretty well organized (functions, aliases, and exports) into pieces that according to the docs would be easy to translate.

I'm certain there's a cleaner, more testable/sturdy way to do this, but for my purposes of trying this out, it worked fine to get me started with the things I use most often.

Rather than a .bashrc, you'll be putting these into ~/.config/fish/functions/, and I broke these pieces of my profile out into files like exports.fish, etc.

Since aliases can remain the same, I just grep'd my aliases out first:

grep alias bashrc | tee -a ~/.config/fish/functions/aliases.fish
Enter fullscreen mode Exit fullscreen mode

For exports, the format for a value like export PATH=$PATH:/usr/bin becomes set -x PATH $PATH:/usr/bin, so like the above, I start by pulling out those values and reformatting:

cat bashrc | sed -e 's|export|set -x|g' -e 's|=| |'g | tee -a ~/.config/fish/functions/exports.fish
Enter fullscreen mode Exit fullscreen mode

The tricky one was functions. Imagine for a function like:

function cd_mount {
    if [ -f $1 ]; then \
        if [ -d $2 ]; then \
            sudo mount -o loop $1 $2
        fi
    fi
}
Enter fullscreen mode Exit fullscreen mode

small things change like removing the then keyword, and for instances of fi or done in conditionals or loops, or the braces in a function, you use the end keyword. So, the cd_mount function becomes:

function cd_mount  
    if [ -f $1 ]; then
        if [ -d $2 ]; then
            sudo mount -o loop $1 $2;
        fi;
    fi
end
Enter fullscreen mode Exit fullscreen mode

So,I'm going to do this by finding the name of each function in my bashrc, then for each one, finding the definition, and using sed to reformat the relevant parts of the structure:

for f in $(grep function bashrc | sed -e 's|function ||'g -e 's|()||g' -e 's|{||g'); do 
    declare -f $f | sed -e 's|()||g' \
    -e 's|{||g' -e 's|}|end|g' \
    | sed -e "0,/$f/{s//function $f/}" \
    | tee -a functions.fish; 
done
Enter fullscreen mode Exit fullscreen mode

Of course, this one requires a lot more work to fix the internals of each function (conditionals, use of variables, etc.) to write a full conversion script, but with some inclusion of the above, I was able to correct this with minimal effort by hand after this which saved a lot of the upfront work.

Discussion (0)