In this article, we will explore how to create and save fish shell functions on the fly.
This is useful if you need to automate things in the shell.
Tested on fish version: 3.0.2
$ funced function hello echo hello world end
Tip: If you have
$EDITORconfigured, it will open that instead
Hitting Enter will save the function
hello into this session. Running
hello will echo "hello world".
This function will only be available for this session. It will not be saved for future sessions.
To save our
hello function so that we can use it in future sessions, we use
This will save
hello into a file in our configuration directory, where it will automatically be loaded for future sessions.
You can see this function saved in
It's always good to document our functions, especially if we are writing it with the intent to share with other people. For that, we use the
funced hello to edit the previously defined
hello function. Now we can make any changes and use
funcsave if we want to save it.
Continuing our previous example we can define a description option to set a description for our function.
Tip: you can use
-das a shortcut to
If we want to make our
hello function say what we want, we can use arguments!
In our function, we have access to
$argv which is a variable list of arguments that the function received.
This is a welcomed changed from bash which has numbered variables like
$1 to access the first argument of the function.
If we wanted the first argument of a function, we simply call
Note: Fish shell indices start at 1, not 0. Fish tries to be modern this way.
To make it more readable, we can use named arguments. This is much friendlier to read compared to
-a option allows us to specify variable names for arguments that we specify.
$name correspond to the first and second arguments of the
I hope you learned a new thing about the fish shell and how to write your own functions! You can always read more about fish shell functions here.
Until then, keep learning!