⬸ more blog posts

writing fish functions

Use fish (shell for mac) to create your own functions, for example, this shortcut to hide all your desktop icons.

This tutorial walks through how to do create your own command line function for fish shell, by creating a function to quickly hide all the icons on your desktop.

I create functions when I find myself looking up how to do something I've researched/learned before. This function came about as a way to "turn off" the desktop, hiding everything but the background image. 99% of the time it is fine to have the desktop off, but there are occasional reasons where I want to see it (seeing mounted CDs, for example).

Prerequisites: You use fish, a command-line shell for Mac - https://fishshell.com

creating the "toggle desktop" function in fish

1. create your function file

Create a new file for your function in the fish functions folder. Name this file what you want the function to be called. In this case, the function will be called toggle_desktop.

cd ~/.config/fish/functions/ nano toggle_desktop.fish

Nano is a basic text editor to edit files inside the command line. If you'd prefer, you can use any text editor to edit the file, just make sure you save it into that folder.

2. write your function

In this case we look for an argument on the function and switch based on the argument. We also give helpful hints if they don't get the syntax right.

function toggle_desktop
    if set -q argv[1]
      switch $argv
        case off
           echo 'turning desktop off'
           defaults write com.apple.finder CreateDesktop -bool false
           killall Finder
           echo "your desktop is now off"
        case on
           echo 'turning desktop on'
           defaults write com.apple.finder CreateDesktop -bool true
           killall Finder
           echo "your desktop is now on"
        case '*'
           echo 'hmm, did you mean "on" or "off"?'
         echo 'did you mean "toggle_desktop on"?'

3. save your function

ctrl-x (quit), y (save)

4. open a new terminal window

Fish won't pick up your changes until you open a new terminal window. This can be very confusing when you are debugging!

5. try toggle_desktop off

Your desktop should turn off. Great!

next steps

Curious about other functions fish has? Enter functions to see a list. functions + <function-name> will show you how it works and where it is defined, useful for copying!

This function works fine as it is, but an enhancement would be to toggle automatically based on the current state, so that the user doesn't need pass an argument, i.e. if it's on, guess that you want to turn it off.

published jan 13, 2019

want updates from hq.network?

We respect your privacy.