FISH-DOC(1) fish-shell FISH-DOC(1)
This is the documentation for fish, the friendly interactive shell.
A shell is a program that helps you operate your computer by starting other
programs. fish offers a command-line interface focused on usability and
interactive use.
Some of the special features of fish are:
o Extensive UI: Syntax highlighting, Autosuggestions, tab completion
and selection lists that can be navigated and filtered.
o No configuration needed: fish is designed to be ready to use
immediately, without requiring extensive configuration.
o Easy scripting: New functions can be added on the fly. The syntax is
easy to learn and use.
This page explains how to install and set up fish and where to get more
information.
WHERE TO GO?
If this is your first time using fish, see the tutorial.
If you are already familiar with other shells like bash and want to see
the scripting differences, see Fish For Bash Users.
For an overview of fish's scripting language, see The Fish Language. If
it would be useful in a script file, it's here.
For information on using fish interactively, see Interactive use. If
it's about key presses, syntax highlighting or anything else that needs
an interactive terminal session, look here.
If you need to install fish first, read on, the rest of this document
will tell you how to get, install and configure fish.
INSTALLATION
This section describes how to install, uninstall, start, and exit fish.
It also explains how to make fish the default shell.
Installation
Up-to-date instructions for installing the latest version of fish are
on the fish homepage .
To install the development version of fish, see the instructions on the
project's GitHub page .
Starting and Exiting
Once fish has been installed, open a terminal. If fish is not the
default shell:
o Type fish to start a shell:
> fish
o Type exit to end the session:
> exit
Default Shell
There are multiple ways to switch to fish (or any other shell) as your
default.
The simplest method is to set your terminal emulator (eg GNOME
Terminal, Apple's Terminal.app, or Konsole) to start fish directly. See
its configuration and set the program to start to /usr/local/bin/fish
(if that's where fish is installed - substitute another location as
appropriate).
Alternatively, you can set fish as your login shell so that it will be
started by all terminal logins, including SSH.
WARNING:
Setting fish as your login shell may cause issues, such as an
incorrect PATH. Some operating systems, including a number of Linux
distributions, require the login shell to be Bourne-compatible and
to read configuration from /etc/profile. fish may not be suitable as
a login shell on these systems.
To change your login shell to fish:
1. Add the shell to /etc/shells with:
> echo /usr/local/bin/fish | sudo tee -a /etc/shells
2. Change your default shell with:
> chsh -s /usr/local/bin/fish
Again, substitute the path to fish for /usr/local/bin/fish - see
command -s fish inside fish. To change it back to another shell, just
substitute /usr/local/bin/fish with /bin/bash, /bin/tcsh or /bin/zsh as
appropriate in the steps above.
Uninstalling
For uninstalling fish: see FAQ: Uninstalling fish.
Shebang Line
Because shell scripts are written in many different languages, they
need to carry information about which interpreter should be used to
execute them. For this, they are expected to have a first line, the
shebang line, which names the interpreter executable.
A script written in bash would need a first line like this:
#!/bin/bash
When the shell tells the kernel to execute the file, it will use the
interpreter /bin/bash.
For a script written in another language, just replace /bin/bash with
the interpreter for that language. For example: /usr/bin/python for a
python script, or /usr/local/bin/fish for a fish script, if that is
where you have them installed.
If you want to share your script with others, you might want to use env
to allow for the interpreter to be installed in other locations. For
example:
#!/usr/bin/env fish
echo Hello from fish $version
This will call env, which then goes through PATH to find a program
called "fish". This makes it work, whether fish is installed in (for
example) /usr/local/bin/fish, /usr/bin/fish, or ~/.local/bin/fish, as
long as that directory is in PATH.
The shebang line is only used when scripts are executed without
specifying the interpreter. For functions inside fish or when executing
a script with fish /path/to/script, a shebang is not required (but it
doesn't hurt!).
When executing files without an interpreter, fish, like other shells,
tries your system shell, typically /bin/sh. This is needed because some
scripts are shipped without a shebang line.
CONFIGURATION
To store configuration write it to a file called
~/.config/fish/config.fish.
.fish scripts in ~/.config/fish/conf.d/ are also automatically executed
before config.fish.
These files are read on the startup of every shell, whether interactive
and/or if they're login shells. Use status --is-interactive and status
--is-login to do things only in interactive/login shells, respectively.
This is the short version; for a full explanation, like for sysadmins
or integration for developers of other software, see Configuration
files.
If you want to see what you changed over fish's defaults, see
fish_delta.
Examples:
To add ~/linux/bin to PATH variable when using a login shell, add this
to ~/.config/fish/config.fish file:
if status --is-login
set -gx PATH $PATH ~/linux/bin
end
This is just an example; using fish_add_path e.g. fish_add_path
~/linux/bin which only adds the path if it isn't included yet is
easier.
To run commands on exit, use an event handler that is triggered by the
exit of the shell:
function on_exit --on-event fish_exit
echo fish is now exiting
end
RESOURCES
o The GitHub page
o The official Gitter channel
o The official mailing list at fish-users@lists.sourceforge.net
If you have an improvement for fish, you can submit it via the GitHub
page.
OTHER HELP PAGES
Frequently asked questions
What is the equivalent to this thing from bash (or other shells)?
See Fish for bash users
How do I set or clear an environment variable?
Use the set command:
set -x key value # typically set -gx key value
set -e key
Since fish 3.1 you can set an environment variable for just one command
using the key=value some command syntax, like in other shells. The two
lines below behave identically - unlike other shells, fish will output
value both times:
key=value echo $key
begin; set -lx key value; echo $key; end
Note that "exported" is not a scope, but an additional bit of state. A
variable can be global and exported or local and exported or even
universal and exported. Typically it makes sense to make an exported
variable global.
How do I check whether a variable is defined?
Use set -q var. For example, if set -q var; echo variable defined;
end. To check multiple variables you can combine with and and or like
so:
if set -q var1; or set -q var2
echo either variable defined
end
Keep in mind that a defined variable could also be empty, either by
having no elements (if set like set var) or only empty elements (if set
like set var ""). Read on for how to deal with those.
How do I check whether a variable is not empty?
Use string length -q -- $var. For example, if string length -q --
$var; echo not empty; end. Note that string length will interpret a
list of multiple variables as a disjunction (meaning any/or):
if string length -q -- $var1 $var2 $var3
echo at least one of these variables is not empty
end
Alternatively, use test -n "$var", but remember that the variable must
be double-quoted. For example, if test -n "$var"; echo not empty; end.
The test command provides its own and (-a) and or (-o):
if test -n "$var1" -o -n "$var2" -o -n "$var3"
echo at least one of these variables is not empty
end
If you want to know if a variable has no elements, use set -q var[1].
Why doesn't set -Ux (exported universal variables) seem to work?
A global variable of the same name already exists.
Environment variables such as EDITOR or TZ can be set universally using
set -Ux. However, if there is an environment variable already set
before fish starts (such as by login scripts or system administrators),
it is imported into fish as a global variable. The variable scopes are
searched from the "inside out", which means that local variables are
checked first, followed by global variables, and finally universal
variables.
This means that the global value takes precedence over the universal
value.
To avoid this problem, consider changing the setting which fish
inherits. If this is not possible, add a statement to your
configuration file (usually ~/.config/fish/config.fish):
set -gx EDITOR vim
How do I run a command every login? What's fish's equivalent to .bashrc or
.profile?
Edit the file ~/.config/fish/config.fish [1], creating it if it does
not exist (Note the leading period).
Unlike .bashrc and .profile, this file is always read, even in
non-interactive or login shells.
To do something only in interactive shells, check status is-interactive
like:
if status is-interactive
# use the coolbeans theme
fish_config theme choose coolbeans
end
[1] The "~/.config" part of this can be set via $XDG_CONFIG_HOME,
that's just the default.
How do I set my prompt?
The prompt is the output of the fish_prompt function. Put it in
~/.config/fish/functions/fish_prompt.fish. For example, a simple prompt
is:
function fish_prompt
set_color $fish_color_cwd
echo -n (prompt_pwd)
set_color normal
echo -n ' > '
end
You can also use the Web configuration tool, fish_config, to preview
and choose from a gallery of sample prompts.
Or you can use fish_config from the commandline:
> fish_config prompt show
# displays all the prompts fish ships with
> fish_config prompt choose disco
# loads the disco prompt in the current shell
> fish_config prompt save
# makes the change permanent
If you want to modify your existing prompt, you can use funced and
funcsave like:
>_ funced fish_prompt
# This opens up your editor (set in $EDITOR).
# Modify the function,
# save the file and repeat to your liking.
# Once you are happy with it:
>_ funcsave fish_prompt
This also applies to fish_right_prompt and fish_mode_prompt.
Why does my prompt show a [I]?
That's the fish_mode_prompt. It is displayed by default when you've
activated vi mode using fish_vi_key_bindings.
If you haven't activated vi mode on purpose, you might have installed a
third-party theme or plugin that does it.
If you want to change or disable this display, modify the
fish_mode_prompt function, for instance via funced.
How do I customize my syntax highlighting colors?
Use the web configuration tool, fish_config, or alter the fish_color
family of environment variables.
You can also use fish_config on the commandline, like:
> fish_config theme show
# to demonstrate all the colorschemes
> fish_config theme choose coolbeans
# to load the "coolbeans" theme
> fish_config theme save
# to make the change permanent
How do I change the greeting message?
Change the value of the variable fish_greeting or create a
fish_greeting function. For example, to remove the greeting use:
set -U fish_greeting
Or if you prefer not to use a universal variable, use:
set -g fish_greeting
in config.fish.
How do I run a command from history?
Type some part of the command, and then hit the up (^) or down (v)
arrow keys to navigate through history matches, or press ctrl-r to open
the history in a searchable pager. In this pager you can press ctrl-r
or ctrl-s to move to older or younger history respectively.
Additional default key bindings include ctrl-p (up) and ctrl-n (down).
See Searchable command history for more information.
Why doesn't history substitution ("!$" etc.) work?
Because history substitution is an awkward interface that was invented
before interactive line editing was even possible. Instead of adding
this pseudo-syntax, fish opts for nice history searching and recall
features. Switching requires a small change of habits: if you want to
modify an old line/word, first recall it, then edit.
As a special case, most of the time history substitution is used as
sudo !!. In that case just press alt-s, and it will recall your last
commandline with sudo prefixed (or toggle a sudo prefix on the current
commandline if there is anything).
In general, fish's history recall works like this:
o Like other shells, the Up arrow, up recalls whole lines, starting
from the last executed line. So instead of typing !!, you would just
hit the up-arrow.
o If the line you want is far back in the history, type any part of the
line and then press Up one or more times. This will filter the
recalled lines to ones that include this text, and you will get to
the line you want much faster. This replaces "!vi", "!?bar.c" and
the like. If you want to see more context, you can press ctrl-r to
open the history in the pager.
o alt-up recalls individual arguments, starting from the last argument
in the last executed line. This can be used instead of "!$".
See documentation for more details about line editing in fish.
That being said, you can use Abbreviations to implement history
substitution. Here's just !!:
function last_history_item; echo $history[1]; end
abbr -a !! --position anywhere --function last_history_item
Run this and !! will be replaced with the last history entry, anywhere
on the commandline. Put it into config.fish to keep it.
How do I run a subcommand? The backtick doesn't work!
fish uses parentheses for subcommands. For example:
for i in (ls)
echo $i
end
It also supports the familiar $() syntax, even in quotes. Backticks are
not supported because they are discouraged even in POSIX shells. They
nest poorly and are hard to tell from single quotes ('').
My command (pkg-config) gives its output as a single long string?
Unlike other shells, fish splits command substitutions only on
newlines, not spaces or tabs or the characters in $IFS.
That means if you run
count (printf '%s ' a b c)
It will print 1, because the "a b c " is used in one piece. But if you
do
count (printf '%s\n' a b c)
it will print 3, because it gave count the arguments "a", "b" and "c"
separately.
In the overwhelming majority of cases, splitting on spaces is unwanted,
so this is an improvement. This is why you hear about problems with
filenames with spaces, after all.
However sometimes, especially with pkg-config and related tools,
splitting on spaces is needed.
In these cases use string split -n " " like:
g++ example_01.cpp (pkg-config --cflags --libs gtk+-2.0 | string split -n " ")
The -n is so empty elements are removed like POSIX shells would do.
How do I get the exit status of a command?
Use the $status variable. This replaces the $? variable used in other
shells.
somecommand
if test $status -eq 7
echo "That's my lucky number!"
end
If you are just interested in success or failure, you can run the
command directly as the if-condition:
if somecommand
echo "Command succeeded"
else
echo "Command failed"
end
Or if you just want to do one command in case the first succeeded or
failed, use and or or:
somecommand
or someothercommand
See the Conditions and the documentation for test and if for more
information.
My command prints "No matches for wildcard" but works in bash
In short: quote or escape the wildcard:
scp user@ip:/dir/"string-*"
When fish sees an unquoted *, it performs wildcard expansion. That
means it tries to match filenames to the given string.
If the wildcard doesn't match any files, fish prints an error instead
of running the command:
> echo *this*does*not*exist
fish: No matches for wildcard '*this*does*not*exist'. See `help expand`.
echo *this*does*not*exist
^
Now, bash also tries to match files in this case, but when it doesn't
find a match, it passes along the literal wildcard string instead.
That means that commands like the above
scp user@ip:/dir/string-*
or
apt install postgres-*
appear to work, because most of the time the string doesn't match and
so it passes along the string-*, which is then interpreted by the
receiving program.
But it also means that these commands can stop working at any moment
once a matching file is encountered (because it has been created or the
command is executed in a different working directory), and to deal with
that bash needs workarounds like
for f in ./*.mpg; do
# We need to test if the file really exists because
# the wildcard might have failed to match.
test -f "$f" || continue
mympgviewer "$f"
done
(from http://mywiki.wooledge.org/BashFAQ/004)
For these reasons, fish does not do this, and instead expects asterisks
to be quoted or escaped if they aren't supposed to be expanded.
This is similar to bash's "failglob" option.
Why won't SSH/SCP/rsync connect properly when fish is my login shell?
This problem may show up as messages like "Received message too long",
"open terminal failed: not a terminal", "Bad packet length", or
"Connection refused" with strange output in ssh_exchange_identification
messages in the debug log.
This usually happens because fish reads the user configuration file
(~/.config/fish/config.fish) always, whether it's in an interactive or
login or non-interactive or non-login shell.
This simplifies matters, but it also means when config.fish generates
output, it will do that even in non-interactive shells like the one
ssh/scp/rsync start when they connect.
Anything in config.fish that produces output should be guarded with
status is-interactive (or status is-login if you prefer):
if status is-interactive
...
end
The same applies for example when you start tmux in config.fish without
guards, which will cause a message like sessions should be nested with
care, unset $TMUX to force.
I'm getting weird graphical glitches (a staircase effect, ghost characters,
cursor in the wrong position,...)?
In a terminal, the application running inside it and the terminal
itself need to agree on the width of characters in order to handle
cursor movement.
This is more important to fish than other shells because features like
syntax highlighting and autosuggestions are implemented by moving the
cursor.
Sometimes, there is disagreement on the width. There are numerous
causes and fixes for this:
o It is possible the character is simply too new for your system to
know - in this case you need to refrain from using it.
o Fish or your terminal might not know about the character or handle it
wrong - in this case fish or your terminal needs to be fixed, or you
need to update to a fixed version.
o The character has an "ambiguous" width and fish thinks that means a
width of X while your terminal thinks it's Y. In this case you either
need to change your terminal's configuration or set
$fish_ambiguous_width to the correct value.
o The character is an emoji and the host system only supports Unicode
8, while you are running the terminal on a system that uses Unicode
>= 9. In this case set $fish_emoji_width to 2.
This also means that a few things are unsupportable:
o Non-monospace fonts - there is no way for fish to figure out what
width a specific character has as it has no influence on the
terminal's font rendering.
o Different widths for multiple ambiguous width characters - there is
no way for fish to know which width you assign to each character.
Uninstalling fish
If you want to uninstall fish, first make sure fish is not set as your
shell. Run chsh -s /bin/bash if you are not sure.
If you installed it with a package manager, just use that package
manager's uninstall function. If you built fish yourself, assuming you
installed it to /usr/local, do this:
rm -Rf /usr/local/etc/fish /usr/local/share/fish ~/.config/fish
rm /usr/local/share/man/man1/fish*.1
cd /usr/local/bin
rm -f fish fish_indent
Interactive use
Fish prides itself on being really nice to use interactively. That's
down to a few features we'll explain in the next few sections.
Fish is used by giving commands in the fish language, see The Fish
Language for information on that.
Help
Fish has an extensive help system. Use the help command to obtain help
on a specific subject or command. For instance, writing help syntax
displays the syntax section of this documentation.
Fish also has man pages for its commands, and translates the help pages
to man pages. For example, man set will show the documentation for set
as a man page.
Help on a specific builtin can also be obtained with the -h parameter.
For instance, to obtain help on the fg builtin, either type fg -h or
help fg.
The main page can be viewed via help index (or just help) or man
fish-doc. The tutorial can be viewed with help tutorial or man
fish-tutorial.
Autosuggestions
fish suggests commands as you type, based on command history,
completions, and valid file paths. As you type commands, you will see a
suggestion offered after the cursor, in a muted gray color (which can
be changed with the fish_color_autosuggestion variable).
To accept the autosuggestion (replacing the command line contents),
press right (->) or ctrl-f. To accept the first suggested word, press
alt-right (->) or alt-f. If the autosuggestion is not what you want,
just ignore it: it won't execute unless you accept it.
Autosuggestions are a powerful way to quickly summon frequently entered
commands, by typing the first few characters. They are also an
efficient technique for navigating through directory hierarchies.
If you don't like autosuggestions, you can disable them by setting
$fish_autosuggestion_enabled to 0:
set -g fish_autosuggestion_enabled 0
Tab Completion
Tab completion is a time saving feature of any modern shell. When you
type tab, fish tries to guess the rest of the word under the cursor. If
it finds just one possibility, it inserts it. If it finds more, it
inserts the longest unambiguous part and then opens a menu (the
"pager") that you can navigate to find what you're looking for.
The pager can be navigated with the arrow keys, pageup / pagedown, tab
or shift-tab. Pressing ctrl-s (the pager-toggle-search binding - / in
vi mode) opens up a search menu that you can use to filter the list.
Fish provides some general purpose completions, like for commands,
variable names, usernames or files.
It also provides a large number of program specific scripted
completions. Most of these completions are simple options like the -l
option for ls, but a lot are more advanced. For example:
o man and whatis show the installed manual pages as completions.
o make uses targets in the Makefile in the current directory as
completions.
o mount uses mount points specified in fstab as completions.
o apt, rpm and yum show installed or installable packages
You can also write your own completions or install some you got from
someone else. For that, see Writing your own completions.
Completion scripts are loaded on demand, just like functions are. The
difference is the $fish_complete_path list is used instead of
$fish_function_path. Typically you can drop new completions in
~/.config/fish/completions/name-of-command.fish and fish will find them
automatically.
Syntax highlighting
Fish interprets the command line as it is typed and uses syntax
highlighting to provide feedback. The most important feedback is the
detection of potential errors. By default, errors are marked red.
Detected errors include:
o Non-existing commands.
o Reading from or appending to a non-existing file.
o Incorrect use of output redirects
o Mismatched parenthesis
To customize the syntax highlighting, you can set the environment
variables listed in the Variables for changing highlighting colors
section.
Fish also provides pre-made color themes you can pick with fish_config.
Running just fish_config opens a browser interface, or you can use
fish_config theme in the terminal.
For example, to disable nearly all coloring:
fish_config theme choose None
Or, to see all themes, right in your terminal:
fish_config theme show
Syntax highlighting variables
The colors used by fish for syntax highlighting can be configured by
changing the values of various variables. The value of these variables
can be one of the colors accepted by the set_color command. The
modifier switches accepted by set_color like --bold, --dim, --italics,
--reverse and --underline are also accepted.
Example: to make errors highlighted and red, use:
set fish_color_error red --bold
The following variables are available to change the highlighting colors
in fish:
+---------------------------+----------------------------+
|Variable | Meaning |
+---------------------------+----------------------------+
|0.0 fish_color_normal | default color |
|168u | |
+---------------------------+----------------------------+
|0.0 fish_color_command | commands like echo |
|168u | |
+---------------------------+----------------------------+
|0.0 fish_color_keyword | keywords like if - this |
|168u | falls back on the command |
| | color if unset |
+---------------------------+----------------------------+
|0.0 fish_color_quote | quoted text like "abc" |
|168u | |
+---------------------------+----------------------------+
|0.0 | IO redirections like |
|fish_color_redirection | >/dev/null |
|168u | |
+---------------------------+----------------------------+
|0.0 fish_color_end 168u | process separators like ; |
| | and & |
+---------------------------+----------------------------+
|0.0 fish_color_error | syntax errors |
|168u | |
+---------------------------+----------------------------+
|0.0 fish_color_param | ordinary command |
|168u | parameters |
+---------------------------+----------------------------+
|0.0 fish_color_valid_path | parameters that are |
|168u | filenames (if the file |
| | exists) |
+---------------------------+----------------------------+
|0.0 fish_color_option | options starting with "-", |
|168u | up to the first "--" |
| | parameter |
+---------------------------+----------------------------+
|0.0 fish_color_comment | comments like '# |
|168u | important' |
+---------------------------+----------------------------+
|0.0 fish_color_selection | selected text in vi visual |
|168u | mode |
+---------------------------+----------------------------+
|0.0 fish_color_operator | parameter expansion |
|168u | operators like * and ~ |
+---------------------------+----------------------------+
|0.0 fish_color_escape | character escapes like \n |
|168u | and \x70 |
+---------------------------+----------------------------+
|0.0 | autosuggestions (the |
|fish_color_autosuggestion | proposed rest of a |
|168u | command) |
+---------------------------+----------------------------+
|0.0 fish_color_cwd 168u | the current working |
| | directory in the default |
| | prompt |
+---------------------------+----------------------------+
|0.0 fish_color_cwd_root | the current working |
|168u | directory in the default |
| | prompt for the root user |
+---------------------------+----------------------------+
|0.0 fish_color_user 168u | the username in the |
| | default prompt |
+---------------------------+----------------------------+
|0.0 fish_color_host 168u | the hostname in the |
| | default prompt |
+---------------------------+----------------------------+
|0.0 | the hostname in the |
|fish_color_host_remote | default prompt for remote |
|168u | sessions (like ssh) |
+---------------------------+----------------------------+
|0.0 fish_color_status | the last command's nonzero |
|168u | exit code in the default |
| | prompt |
+---------------------------+----------------------------+
|0.0 fish_color_cancel | the '^C' indicator on a |
|168u | canceled command |
+---------------------------+----------------------------+
|0.0 | history search matches and |
|fish_color_search_match | selected pager items |
|168u | (background only) |
+---------------------------+----------------------------+
|0.0 | the current position in |
|fish_color_history_current | the history for commands |
|168u | like dirh and cdh |
+---------------------------+----------------------------+
If a variable isn't set or is empty, fish usually tries
$fish_color_normal, except for:
o $fish_color_keyword, where it tries $fish_color_command first.
o $fish_color_option, where it tries $fish_color_param first.
o For $fish_color_valid_path, if that doesn't have a color, but only
modifiers, it adds those to the color that would otherwise be used,
like $fish_color_param. But if valid paths have a color, it uses that
and adds in modifiers from the other color.
Pager color variables
fish will sometimes present a list of choices in a table, called the
pager.
Example: to set the background of each pager row, use:
set fish_pager_color_background --background=white
To have black text on alternating white and gray backgrounds:
set fish_pager_color_prefix black
set fish_pager_color_completion black
set fish_pager_color_description black
set fish_pager_color_background --background=white
set fish_pager_color_secondary_background --background=brwhite
Variables affecting the pager colors:
+---------------------------------------+----------------------------+
|Variable | Meaning |
+---------------------------------------+----------------------------+
|0.0 fish_pager_color_progress 168u | the progress bar at the |
| | bottom left corner |
+---------------------------------------+----------------------------+
|0.0 fish_pager_color_background 168u | the background color of a |
| | line |
+---------------------------------------+----------------------------+
|0.0 fish_pager_color_prefix 168u | the prefix string, i.e. |
| | the string that is to be |
| | completed |
+---------------------------------------+----------------------------+
|0.0 fish_pager_color_completion 168u | the completion itself, |
| | i.e. the proposed rest of |
| | the string |
+---------------------------------------+----------------------------+
|0.0 fish_pager_color_description | the completion description |
|168u | |
+---------------------------------------+----------------------------+
|0.0 | background of the selected |
|fish_pager_color_selected_background | completion |
|168u | |
+---------------------------------------+----------------------------+
|0.0 fish_pager_color_selected_prefix | prefix of the selected |
|168u | completion |
+---------------------------------------+----------------------------+
|0.0 | suffix of the selected |
|fish_pager_color_selected_completion | completion |
|168u | |
+---------------------------------------+----------------------------+
|0.0 | description of the |
|fish_pager_color_selected_description | selected completion |
|168u | |
+---------------------------------------+----------------------------+
|0.0 | background of every second |
|fish_pager_color_secondary_background | unselected completion |
|168u | |
+---------------------------------------+----------------------------+
|0.0 fish_pager_color_secondary_prefix | prefix of every second |
|168u | unselected completion |
+---------------------------------------+----------------------------+
|0.0 | suffix of every second |
|fish_pager_color_secondary_completion | unselected completion |
|168u | |
+---------------------------------------+----------------------------+
|0.0 | description of every |
|fish_pager_color_secondary_description | second unselected |
|168u | completion |
+---------------------------------------+----------------------------+
When the secondary or selected variables aren't set or are empty, the
normal variables are used, except for
$fish_pager_color_selected_background, where the background of
$fish_color_search_match is tried first.
Abbreviations
To avoid needless typing, a frequently-run command like git checkout
can be abbreviated to gco using the abbr command.
abbr -a gco git checkout
After entering gco and pressing space or enter, a gco in command
position will turn into git checkout in the command line. If you want
to use a literal gco sometimes, use ctrl-space [1].
Abbreviations are a lot more powerful than just replacing literal
strings. For example you can make going up a number of directories
easier with this:
function multicd
echo cd (string repeat -n (math (string length -- $argv[1]) - 1) ../)
end
abbr --add dotdot --regex '^\.\.+$' --function multicd
Now, .. transforms to cd ../, while ... turns into cd ../../ and ....
expands to cd ../../../.
The advantage over aliases is that you can see the actual command
before using it, add to it or change it, and the actual command will be
stored in history.
[1] Any binding that executes the expand-abbr or execute bind function
will expand abbreviations. By default ctrl-space is bound to just
inserting a space.
Programmable prompt
When it is fish's turn to ask for input (like after it started or the
command ended), it will show a prompt. Often this looks something like:
you@hostname ~>
This prompt is determined by running the fish_prompt and
fish_right_prompt functions.
The output of the former is displayed on the left and the latter's
output on the right side of the terminal. For vi mode, the output of
fish_mode_prompt will be prepended on the left.
Fish ships with a few prompts which you can see with fish_config. If
you run just fish_config it will open a web interface [2] where you'll
be shown the prompts and can pick which one you want. fish_config
prompt show will show you the prompts right in your terminal.
For example fish_config prompt choose disco will temporarily select the
"disco" prompt. If you like it and decide to keep it, run fish_config
prompt save.
You can also change these functions yourself by running funced
fish_prompt and funcsave fish_prompt once you are happy with the result
(or fish_right_prompt if you want to change that).
[2] The web interface runs purely locally on your computer and
requires python to be installed.
Configurable greeting
When it is started interactively, fish tries to run the fish_greeting
function. The default fish_greeting prints a simple message. You can
change its text by changing the $fish_greeting variable, for instance
using a universal variable:
set -U fish_greeting
or you can set it globally in config.fish:
set -g fish_greeting 'Hey, stranger!'
or you can script it by changing the function:
function fish_greeting
random choice "Hello!" "Hi" "G'day" "Howdy"
end
save this in config.fish or a function file. You can also use funced
and funcsave to edit it easily.
Programmable title
When using most terminals, it is possible to set the text displayed in
the titlebar of the terminal window. Fish does this by running the
fish_title function. It is executed before and after a command and the
output is used as a titlebar message.
The status current-command builtin will always return the name of the
job to be put into the foreground (or fish if control is returning to
the shell) when the fish_title function is called. The first argument
will contain the most recently executed foreground command as a string.
The default title shows the hostname if connected via ssh, the
currently running command (unless it is fish) and the current working
directory. All of this is shortened to not make the tab too wide.
Examples:
To show the last command and working directory in the title:
function fish_title
# `prompt_pwd` shortens the title. This helps prevent tabs from becoming very wide.
echo $argv[1] (prompt_pwd)
pwd
end
Command line editor
The fish editor features copy and paste, a searchable history and many
editor functions that can be bound to special keyboard shortcuts.
Like bash and other shells, fish includes two sets of keyboard
shortcuts (or key bindings): one inspired by the Emacs text editor, and
one by the vi text editor. The default editing mode is Emacs. You can
switch to vi mode by running fish_vi_key_bindings and switch back with
fish_default_key_bindings. You can also make your own key bindings by
creating a function and setting the fish_key_bindings variable to its
name. For example:
function fish_hybrid_key_bindings --description \
"Vi-style bindings that inherit emacs-style bindings in all modes"
for mode in default insert visual
fish_default_key_bindings -M $mode
end
fish_vi_key_bindings --no-erase
end
set -g fish_key_bindings fish_hybrid_key_bindings
While the key bindings included with fish include many of the shortcuts
popular from the respective text editors, they are not a complete
implementation. They include a shortcut to open the current command
line in your preferred editor (alt-e by default) if you need the full
power of your editor.
Shared bindings
Some bindings are common across Emacs and vi mode, because they aren't
text editing bindings, or because what vi/Vim does for a particular key
doesn't make sense for a shell.
o tab completes the current token. shift-tab completes the current
token and starts the pager's search mode. tab is the same as ctrl-i.
o left (<-) and right (->) move the cursor left or right by one
character. If the cursor is already at the end of the line, and an
autosuggestion is available, right (->) accepts the autosuggestion.
o enter executes the current commandline or inserts a newline if it's
not complete yet (e.g. a ) or end is missing).
o alt-enter inserts a newline at the cursor position. This is useful to
add a line to a commandline that's already complete.
o alt-left (<-) and alt-right (->) move the cursor one word left or
right (to the next space or punctuation mark), or moves
forward/backward in the directory history if the command line is
empty. If the cursor is already at the end of the line, and an
autosuggestion is available, alt-right (->) (or alt-f) accepts the
first word in the suggestion.
o ctrl-left (<-) and ctrl-right (->) move the cursor one word left or
right. These accept one word of the autosuggestion - the part they'd
move over.
o shift-left (<-) and shift-right (->) move the cursor one word left or
right, without stopping on punctuation. These accept one big word of
the autosuggestion.
o up (^) and down (v) (or ctrl-p and ctrl-n for emacs aficionados)
search the command history for the previous/next command containing
the string that was specified on the commandline before the search
was started. If the commandline was empty when the search started,
all commands match. See the history section for more information on
history searching.
o alt-up (^) and alt-down (v) search the command history for the
previous/next token containing the token under the cursor before the
search was started. If the commandline was not on a token when the
search started, all tokens match. See the history section for more
information on history searching.
o ctrl-c interrupts/kills whatever is running (SIGINT).
o ctrl-d deletes one character to the right of the cursor. If the
command line is empty, ctrl-d will exit fish.
o ctrl-u removes contents from the beginning of line to the cursor
(moving it to the killring).
o ctrl-l clears and repaints the screen.
o ctrl-w removes the previous path component (everything up to the
previous "/", ":" or "@") (moving it to the Copy and paste (Kill
Ring)).
o ctrl-x copies the current buffer to the system's clipboard, ctrl-v
inserts the clipboard contents. (see fish_clipboard_copy and
fish_clipboard_paste)
o alt-d or ctrl-delete moves the next word to the Copy and paste (Kill
Ring).
o alt-d lists the directory history if the command line is empty.
o alt-delete moves the next argument to the Copy and paste (Kill Ring).
o shift-delete removes the current history item or autosuggestion from
the command history.
o alt-h (or f1) shows the manual page for the current command, if one
exists.
o alt-l lists the contents of the current directory, unless the cursor
is over a directory argument, in which case the contents of that
directory will be listed.
o alt-o opens the file at the cursor in a pager. If the cursor is in
command position and the command is a script, it will instead open
that script in your editor. The editor is chosen from the first
available of the $VISUAL or $EDITOR variables.
o alt-p adds the string &| less; to the end of the job under the
cursor. The result is that the output of the command will be paged.
o alt-w prints a short description of the command under the cursor.
o alt-e edits the current command line in an external editor. The
editor is chosen from the first available of the $VISUAL or $EDITOR
variables.
o alt-v Same as alt-e.
o alt-s Prepends sudo to the current commandline. If the commandline is
empty, prepend sudo to the last commandline.
o ctrl-space Inserts a space without expanding an abbreviation. For vi
mode, this only applies to insert-mode.
Emacs mode commands
To enable emacs mode, use fish_default_key_bindings. This is also the
default.
o home or ctrl-a moves the cursor to the beginning of the line.
o end or ctrl-e moves to the end of line. If the cursor is already at
the end of the line, and an autosuggestion is available, end or
ctrl-e accepts the autosuggestion.
o ctrl-b, ctrl-f move the cursor one character left or right or accept
the autosuggestion just like the left (<-) and right (->) shared
bindings (which are available as well).
o alt-b, alt-f move the cursor one word left or right, or accept one
word of the autosuggestion. If the command line is empty, moves
forward/backward in the directory history instead.
o ctrl-n, ctrl-p move the cursor up/down or through history, like the
up and down arrow shared bindings.
o delete or backspace or ctrl-h removes one character forwards or
backwards respectively.
o alt-backspace removes one word backwards. If supported by the
terminal, ctrl-backspace does the same.
o alt-< moves to the beginning of the commandline, alt-> moves to the
end.
o ctrl-k deletes from the cursor to the end of line (moving it to the
Copy and paste (Kill Ring)).
o escape and ctrl-g cancel the current operation. Immediately after an
unambiguous completion this undoes it.
o alt-c capitalizes the current word.
o alt-u makes the current word uppercase.
o ctrl-t transposes the last two characters.
o alt-t transposes the last two words.
o ctrl-z, ctrl-_ (ctrl-/ on some terminals) undo the most recent edit
of the line.
o alt-/ or ctrl-shift-z reverts the most recent undo.
o ctrl-r opens the history in a pager. This will show history entries
matching the search, a few at a time. Pressing ctrl-r again will
search older entries, pressing ctrl-s (that otherwise toggles pager
search) will go to newer entries. The search bar will always be
selected.
You can change these key bindings using the bind builtin.
Vi mode commands
Vi mode allows for the use of vi-like commands at the prompt.
Initially, insert mode is active. escape enters command mode. The
commands available in command, insert and visual mode are described
below. Vi mode shares some bindings with Emacs mode.
To enable vi mode, use fish_vi_key_bindings. It is also possible to
add all Emacs mode bindings to vi mode by using something like:
function fish_user_key_bindings
# Execute this once per mode that emacs bindings should be used in
fish_default_key_bindings -M insert
# Then execute the vi-bindings so they take precedence when there's a conflict.
# Without --no-erase fish_vi_key_bindings will default to
# resetting all bindings.
# The argument specifies the initial mode (insert, "default" or visual).
fish_vi_key_bindings --no-erase insert
end
When in vi mode, the fish_mode_prompt function will display a mode
indicator to the left of the prompt. To disable this feature, override
it with an empty function. To display the mode elsewhere (like in your
right prompt), use the output of the fish_default_mode_prompt function.
When a binding switches the mode, it will repaint the mode-prompt if it
exists, and the rest of the prompt only if it doesn't. So if you want a
mode-indicator in your fish_prompt, you need to erase fish_mode_prompt
e.g. by adding an empty file at
~/.config/fish/functions/fish_mode_prompt.fish. (Bindings that change
the mode are supposed to call the repaint-mode bind function, see bind)
The fish_vi_cursor function will be used to change the cursor's shape
depending on the mode in supported terminals. The following snippet can
be used to manually configure cursors after enabling vi mode:
# Emulates vim's cursor shape behavior
# Set the normal and visual mode cursors to a block
set fish_cursor_default block
# Set the insert mode cursor to a line
set fish_cursor_insert line
# Set the replace mode cursors to an underscore
set fish_cursor_replace_one underscore
set fish_cursor_replace underscore
# Set the external cursor to a line. The external cursor appears when a command is started.
# The cursor shape takes the value of fish_cursor_default when fish_cursor_external is not specified.
set fish_cursor_external line
# The following variable can be used to configure cursor shape in
# visual mode, but due to fish_cursor_default, is redundant here
set fish_cursor_visual block
Additionally, blink can be added after each of the cursor shape
parameters to set a blinking cursor in the specified shape.
Fish knows the shapes "block", "line" and "underscore", other values
will be ignored.
If the cursor shape does not appear to be changing after setting the
above variables, it's likely your terminal emulator does not support
the capabilities necessary to do this.
Command mode
Command mode is also known as normal mode.
o h moves the cursor left.
o l moves the cursor right.
o k and j search the command history for the previous/next command
containing the string that was specified on the commandline before
the search was started. If the commandline was empty when the search
started, all commands match. See the history section for more
information on history searching. In multi-line commands, they move
the cursor up and down respectively.
o i enters insert mode at the current cursor position.
o I enters insert mode at the beginning of the line.
o v enters visual mode at the current cursor position.
o a enters insert mode after the current cursor position.
o A enters insert mode at the end of the line.
o o inserts a new line under the current one and enters insert mode
o O (capital-"o") inserts a new line above the current one and enters
insert mode
o 0 (zero) moves the cursor to beginning of line (remaining in command
mode).
o d,d deletes the current line and moves it to the Copy and paste (Kill
Ring).
o D deletes text after the current cursor position and moves it to the
Copy and paste (Kill Ring).
o p pastes text from the Copy and paste (Kill Ring).
o u undoes the most recent edit of the command line.
o ctrl-r redoes the most recent edit.
o [ and ] search the command history for the previous/next token
containing the token under the cursor before the search was started.
See the history section for more information on history searching.
o / opens the history in a pager. This will show history entries
matching the search, a few at a time. Pressing it again will search
older entries, pressing ctrl-s (that otherwise toggles pager search)
will go to newer entries. The search bar will always be selected.
o backspace moves the cursor left.
o g / G moves the cursor to the beginning/end of the commandline,
respectively.
o :,q exits fish.
Insert mode
o escape enters command mode.
o backspace removes one character to the left.
o ctrl-n accepts the autosuggestion.
Visual mode
o left (``<-`) and right`(``->`) extend the selection backward/forward
by one character.
o h moves the cursor left.
o l moves the cursor right.
o k moves the cursor up.
o j moves the cursor down.
o b and w extend the selection backward/forward by one word.
o d and x move the selection to the Copy and paste (Kill Ring) and
enter command mode.
o escape and ctrl-c enter command mode.
o c and s remove the selection and switch to insert mode.
o X moves the entire line to the Copy and paste (Kill Ring), and enters
command mode.
o y copies the selection to the Copy and paste (Kill Ring), and enters
command mode.
o ~ toggles the case (upper/lower) on the selection, and enters command
mode.
o ",*,y copies the selection to the clipboard, and enters command mode.
Custom bindings
In addition to the standard bindings listed here, you can also define
your own with bind:
# Just clear the commandline on control-c
bind ctrl-c 'commandline -r ""'
Put bind statements into config.fish or a function called
fish_user_key_bindings.
If you change your mind on a binding and want to go back to fish's
default, you can simply erase it again:
bind --erase ctrl-c
Fish remembers its preset bindings and so it will take effect again.
This saves you from having to remember what it was before and add it
again yourself.
If you use vi bindings, note that bind will by default bind keys in
command mode. To bind something in insert mode:
bind --mode insert ctrl-c 'commandline -r ""'
Key sequences
To find out the name of a key, you can use fish_key_reader.
> fish_key_reader # Press Alt + right-arrow
Press a key:
bind alt-right 'do something'
Note that the historical way the terminal encodes keys and sends them
to the application (fish, in this case) makes a lot of combinations
indistinguishable or unbindable. In the usual encoding, ctrl-i is the
same as the tab key, and shift cannot be detected when ctrl is also
pressed.
There are more powerful encoding schemes, and fish tries to tell the
terminal to turn them on, but there are still many terminals that do
not support them. When fish_key_reader prints the same sequence for two
different keys, then that is because your terminal sends the same
sequence for them, and there isn't anything fish can do about it. It is
our hope that these schemes will become more widespread, making input
more flexible.
In the historical scheme, escape is the same thing as alt in a
terminal. To distinguish between pressing escape and then another key,
and pressing alt and that key (or an escape sequence the key sends),
fish waits for a certain time after seeing an escape character. This is
configurable via the fish_escape_delay_ms variable.
If you want to be able to press escape and then a character and have it
count as alt+that character, set it to a higher value, e.g.:
set -g fish_escape_delay_ms 100
Similarly, to disambiguate other keypresses where you've bound a
subsequence and a longer sequence, fish has fish_sequence_key_delay_ms:
# This binds the sequence j,k to switch to normal mode in vi mode.
# If you kept it like that, every time you press "j",
# fish would wait for a "k" or other key to disambiguate
bind -M insert -m default j,k cancel repaint-mode
# After setting this, fish only waits 200ms for the "k",
# or decides to treat the "j" as a separate sequence, inserting it.
set -g fish_sequence_key_delay_ms 200
Copy and paste (Kill Ring)
Fish uses an Emacs-style kill ring for copy and paste functionality.
For example, use ctrl-k (kill-line) to cut from the current cursor
position to the end of the line. The string that is cut (a.k.a. killed
in emacs-ese) is inserted into a list of kills, called the kill ring.
To paste the latest value from the kill ring (emacs calls this
"yanking") use ctrl-y (the yank input function). After pasting, use
alt-y (yank-pop) to rotate to the previous kill.
Copy and paste from outside are also supported, both via the ctrl-x /
ctrl-v bindings (the fish_clipboard_copy and fish_clipboard_paste
functions [3]) and via the terminal's paste function, for which fish
enables "Bracketed Paste Mode", so it can tell a paste from manually
entered text. In addition, when pasting inside single quotes, pasted
single quotes and backslashes are automatically escaped so that the
result can be used as a single token simply by closing the quote after.
Kill ring entries are stored in fish_killring variable.
The commands begin-selection and end-selection (unbound by default;
used for selection in vi visual mode) control text selection together
with cursor movement commands that extend the current selection. The
variable fish_cursor_selection_mode can be used to configure if that
selection should include the character under the cursor (inclusive) or
not (exclusive). The default is exclusive, which works well with any
cursor shape. For vi mode, and particularly for the block or underscore
cursor shapes you may prefer inclusive.
[3] These rely on external tools. Currently xsel, xclip,
wl-copy/wl-paste and pbcopy/pbpaste are supported.
Multiline editing
The fish commandline editor can be used to work on commands that are
several lines long. There are three ways to make a command span more
than a single line:
o Pressing the enter key while a block of commands is unclosed, such as
when one or more block commands such as for, begin or if do not have
a corresponding end command.
o Pressing alt-enter instead of pressing the enter key.
o By inserting a backslash (\) character before pressing the enter key,
escaping the newline.
The fish commandline editor works exactly the same in single line mode
and in multiline mode. To move between lines use the left and right
arrow keys and other such keyboard shortcuts.
Searchable command history
After a command has been executed, it is remembered in the history
list. Any duplicate history items are automatically removed. By
pressing the up and down keys, you can search forwards and backwards in
the history. If the current command line is not empty when starting a
history search, only the commands containing the string entered into
the command line are shown.
By pressing alt-up (^) and alt-down (v), a history search is also
performed, but instead of searching for a complete commandline, each
commandline is broken into separate elements just like it would be
before execution, and the history is searched for an element matching
that under the cursor.
For more complicated searches, you can press ctrl-r to open a pager
that allows you to search the history. It shows a limited number of
entries in one page, press ctrl-r [4] again to move to the next page
and ctrl-s [5] to move to the previous page. You can change the text to
refine your search.
History searches are case-insensitive unless the search string contains
an uppercase character. You can stop a search to edit your search
string by pressing escape or pagedown.
Prefixing the commandline with a space will prevent the entire line
from being stored in the history. It will still be available for recall
until the next command is executed, but will not be stored on disk.
This is to allow you to fix misspellings and such.
The command history is stored in the file
~/.local/share/fish/fish_history (or $XDG_DATA_HOME/fish/fish_history
if that variable is set) by default. However, you can set the
fish_history environment variable to change the name of the history
session (resulting in a _history file); both before starting
the shell and while the shell is running.
See the history command for other manipulations.
Examples:
To search for previous entries containing the word 'make', type make in
the console and press the up key.
If the commandline reads cd m, place the cursor over the m character
and press alt-up (^) to search for previously typed words containing
'm'.
[4] Or another binding that triggers the history-pager input function.
See bind for a list.
[5] Or another binding that triggers the pager-toggle-search input
function.
Private mode
Fish has a private mode, in which command history will not be written
to the history file on disk. To enable it, either set
$fish_private_mode to a non-empty value, or launch with fish --private
(or fish -P for short).
If you launch fish with -P, it both hides old history and prevents
writing history to disk. This is useful to avoid leaking personal
information (e.g. for screencasts) or when dealing with sensitive
information.
You can query the variable fish_private_mode (if test -n
"$fish_private_mode" ...) if you would like to respect the user's wish
for privacy and alter the behavior of your own fish scripts.
Navigating directories
Navigating directories is usually done with the cd command, but fish
offers some advanced features as well.
The current working directory can be displayed with the pwd command, or
the $PWD special variable. Usually your prompt already does this.
Directory history
Fish automatically keeps a trail of the recent visited directories with
cd by storing this history in the dirprev and dirnext variables.
Several commands are provided to interact with this directory history:
o dirh prints the history
o cdh displays a prompt to quickly navigate the history
o prevd moves backward through the history. It is bound to alt-left
(<-)
o nextd moves forward through the history. It is bound to alt-right
(->)
Directory stack
Another set of commands, usually also available in other shells like
bash, deal with the directory stack. Stack handling is not automatic
and needs explicit calls of the following commands:
o dirs prints the stack
o pushd adds a directory on top of the stack and makes it the current
working directory
o popd removes the directory on top of the stack and changes the
current working directory
The fish language
This document is a comprehensive overview of fish's scripting language.
For interactive features see Interactive use.
Syntax overview
Shells like fish are used by giving them commands. A command is
executed by writing the name of the command followed by any arguments.
For example:
echo hello world
echo command writes its arguments to the screen. In this example the
output is hello world.
Everything in fish is done with commands. There are commands for
repeating other commands, commands for assigning variables, commands
for treating a group of commands as a single command, etc. All of these
commands follow the same basic syntax.
Every program on your computer can be used as a command in fish. If the
program file is located in one of the PATH directories, you can just
type the name of the program to use it. Otherwise the whole filename,
including the directory (like /home/me/code/checkers/checkers or
../checkers) is required.
Here is a list of some useful commands:
o cd: Change the current directory
o ls: List files and directories
o man: Display a manual page - try man ls to get help on your "ls"
command, or man mv to get information about "mv".
o mv: Move (rename) files
o cp: Copy files
o open: Open files with the default application associated with each
filetype
o less: Display the contents of files
Commands and arguments are separated by the space character ' '. Every
command ends with either a newline (by pressing the return key) or a
semicolon ;. Multiple commands can be written on the same line by
separating them with semicolons.
A switch is a very common special type of argument. Switches almost
always start with one or more hyphens - and alter the way a command
operates. For example, the ls command usually lists the names of all
files and directories in the current working directory. By using the -l
switch, the behavior of ls is changed to not only display the filename,
but also the size, permissions, owner, and modification time of each
file.
Switches differ between commands and are usually documented on a
command's manual page. There are some switches, however, that are
common to most commands. For example, --help will usually display a
help text, --version will usually display the command version, and -i
will often turn on interactive prompting before taking action. Try man
your-command-here to get information on your command's switches.
So the basic idea of fish is the same as with other unix shells: It
gets a commandline, runs expansions, and the result is then run as a
command.
Terminology
Here we define some of the terms used on this page and throughout the
rest of the fish documentation:
o Argument: A parameter given to a command. In echo foo, the "foo" is
an argument.
o Builtin: A command that is implemented by the shell. Builtins are so
closely tied to the operation of the shell that it is impossible to
implement them as external commands. In echo foo, the "echo" is a
builtin.
o Command: A program that the shell can run, or more specifically an
external program that the shell runs in another process. External
commands are provided on your system, as executable files. In echo
foo the "echo" is a builtin command, in command echo foo the "echo"
is an external command, provided by a file like /bin/echo.
o Function: A block of commands that can be called as if they were a
single command. By using functions, it is possible to string together
multiple simple commands into one more advanced command.
o Job: A running pipeline or command.
o Pipeline: A set of commands strung together so that the output of one
command is the input of the next command. echo foo | grep foo is a
pipeline.
o Redirection: An operation that changes one of the input or output
streams associated with a job.
o Switch or Option: A special kind of argument that alters the behavior
of a command. A switch almost always begins with one or two hyphens.
In echo -n foo the "-n" is an option.
Quotes
Sometimes you want to give a command an argument that contains
characters special to fish, like spaces or $ or *. To do that, you can
use quotes:
rm "my file.txt"
to remove a file called my file.txt instead of trying to remove two
files, my and file.txt.
Fish understands two kinds of quotes: Single (') and double ("), and
both work slightly differently.
Between single quotes, fish performs no expansions. Between double
quotes, fish only performs variable expansion and command substitution
in the $(command). No other kind of expansion (including brace
expansion or parameter expansion) is performed, and escape sequences
(for example, \n) are ignored. Within quotes, whitespace is not used to
separate arguments, allowing quoted arguments to contain spaces.
The only meaningful escape sequences in single quotes are \', which
escapes a single quote and \\, which escapes the backslash symbol. The
only meaningful escapes in double quotes are \", which escapes a double
quote, \$, which escapes a dollar character, \ followed by a newline,
which deletes the backslash and the newline, and \\, which escapes the
backslash symbol.
Single quotes have no special meaning within double quotes and vice
versa.
More examples:
grep 'enabled)$' foo.txt
searches for lines ending in enabled) in foo.txt (the $ is special to
grep: it matches the end of the line).
apt install "postgres-*"
installs all packages with a name starting with "postgres-", instead of
looking through the current directory for files named
"postgres-something".
Escaping Characters
Some characters cannot be written directly on the command line. For
these characters, so-called escape sequences are provided. These are:
o \a represents the alert character.
o \e represents the escape character.
o \f represents the form feed character.
o \n represents a newline character.
o \r represents the carriage return character.
o \t represents the tab character.
o \v represents the vertical tab character.
o \xHH or \XHH, where HH is a hexadecimal number, represents a byte of
data with the specified value. For example, \x9 is the tab character.
If you are using a multibyte encoding, this can be used to enter
invalid strings. Typically fish is run with the ASCII or UTF-8
encoding, so anything up to \X7f is an ASCII character.
o \ooo, where ooo is an octal number, represents the ASCII character
with the specified value. For example, \011 is the tab character. The
highest allowed value is \177.
o \uXXXX, where XXXX is a hexadecimal number, represents the 16-bit
Unicode character with the specified value. For example, \u9 is the
tab character.
o \UXXXXXXXX, where XXXXXXXX is a hexadecimal number, represents the
32-bit Unicode character with the specified value. For example, \U9
is the tab character. The highest allowed value is U10FFFF.
o \cX, where X is a letter of the alphabet, represents the control
sequence generated by pressing the control key and the specified
letter. For example, \ci is the tab character
Some characters have special meaning to the shell. For example, an
apostrophe ' disables expansion (see Quotes). To tell the shell to
treat these characters literally, escape them with a backslash. For
example, the command:
echo \'hello world\'
outputs 'hello world' (including the apostrophes), while the command:
echo 'hello world'
outputs hello world (without the apostrophes). In the former case the
shell treats the apostrophes as literal ' characters, while in the
latter case it treats them as special expansion modifiers.
The special characters and their escape sequences are:
o \ (backslash space) escapes the space character. This keeps the
shell from splitting arguments on the escaped space.
o \$ escapes the dollar character.
o \\ escapes the backslash character.
o \* escapes the star character.
o \? escapes the question mark character (this is not necessary if the
qmark-noglob feature flag is enabled).
o \~ escapes the tilde character.
o \# escapes the hash character.
o \( escapes the left parenthesis character.
o \) escapes the right parenthesis character.
o \{ escapes the left curly bracket character.
o \} escapes the right curly bracket character.
o \[ escapes the left bracket character.
o \] escapes the right bracket character.
o \< escapes the less than character.
o \> escapes the more than character.
o \& escapes the ampersand character.
o \| escapes the vertical bar character.
o \; escapes the semicolon character.
o \" escapes the quote character.
o \' escapes the apostrophe character.
As a special case, \ immediately followed by a literal new line is a
"continuation" and tells fish to ignore the line break and resume input
at the start of the next line (without introducing any whitespace or
terminating a token).
Input/Output Redirection
Most programs use three input/output (I/O) streams:
o Standard input (stdin) for reading. Defaults to reading from the
keyboard.
o Standard output (stdout) for writing output. Defaults to writing to
the screen.
o Standard error (stderr) for writing errors and warnings. Defaults to
writing to the screen.
Each stream has a number called the file descriptor (FD): 0 for stdin,
1 for stdout, and 2 for stderr.
The destination of a stream can be changed using something called
redirection. For example, echo hello > output.txt, redirects the
standard output of the echo command to a text file.
o To read standard input from a file, use DESTINATION.
o To write standard error to a file, use 2>DESTINATION. [1]
o To append standard output to a file, use >>DESTINATION_FILE.
o To append standard error to a file, use 2>>DESTINATION_FILE.
o To not overwrite ("clobber") an existing file, use >?DESTINATION or
2>?DESTINATION. This is known as the "noclobber" redirection.
DESTINATION can be one of the following:
o A filename to write the output to. Often >/dev/null to silence output
by writing it to the special "sinkhole" file.
o An ampersand (&) followed by the number of another file descriptor
like &2 for standard error. The output will be written to the
destination descriptor.
o An ampersand followed by a minus sign (&-). The file descriptor will
be closed. Note: This may cause the program to fail because its
writes will be unsuccessful.
As a convenience, the redirection &> can be used to direct both stdout
and stderr to the same destination. For example, echo hello &>
all_output.txt redirects both stdout and stderr to the file
all_output.txt. This is equivalent to echo hello > all_output.txt 2>&1.
Any arbitrary file descriptor can be used in a redirection by prefixing
the redirection with the FD number.
o To redirect the input of descriptor N, use NDESTINATION.
o To append the output of descriptor N to a file, use
N>>DESTINATION_FILE.
File descriptors cannot be used with a input redirection, only a
regular < one.
For example:
# Write `foo`'s standard error (file descriptor 2)
# to a file called "output.stderr":
foo 2> output.stderr
# if $num doesn't contain a number,
# this test will be false and print an error,
# so by ignoring the error we can be sure that we're dealing
# with a number in the "if" block:
if test "$num" -gt 2 2>/dev/null
# do things with $num as a number greater than 2
else
# do things if $num is <= 2 or not a number
end
# Save `make`s output in a file:
make &>/log
# Redirections stack and can be used with blocks:
begin
echo stdout
echo stderr >&2 # <- this goes to stderr!
end >/dev/null # ignore stdout, so this prints "stderr"
# print all lines that include "foo" from myfile, or nothing if it doesn't exist.
string match '*foo*' | less
will attempt to build fish, and any errors will be shown using the less
pager. [2]
As a convenience, the pipe &| redirects both stdout and stderr to the
same process. This is different from bash, which uses |&.
[2] A "pager" here is a program that takes output and "paginates" it.
less doesn't just do pages, it allows arbitrary scrolling (even
back!).
Combining pipes and redirections
It is possible to use multiple redirections and a pipe at the same
time. In that case, they are read in this order:
1. First the pipe is set up.
2. Then the redirections are evaluated from left-to-right.
This is important when any redirections reference other file
descriptors with the &N syntax. When you say >&2, that will redirect
stdout to where stderr is pointing to at that time.
Consider this helper function:
# Just make a function that prints something to stdout and stderr
function print
echo out
echo err >&2
end
Now let's see a few cases:
# Redirect both stderr and stdout to less
print 2>&1 | less
# or
print &| less
# Show the "out" on stderr, silence the "err"
print >&2 2>/dev/null
# Silence both
print >/dev/null 2>&1
Job control
When you start a job in fish, fish itself will pause, and give control
of the terminal to the program just started. Sometimes, you want to
continue using the commandline, and have the job run in the background.
To create a background job, append an & (ampersand) to your command.
This will tell fish to run the job in the background. Background jobs
are very useful when running programs that have a graphical user
interface.
Example:
emacs &
will start the emacs text editor in the background. fg can be used to
bring it into the foreground again when needed.
Most programs allow you to suspend the program's execution and return
control to fish by pressing ctrl-z (also referred to as ^Z). Once back
at the fish commandline, you can start other programs and do anything
you want. If you then want you can go back to the suspended command by
using the fg (foreground) command.
If you instead want to put a suspended job into the background, use the
bg command.
To get a listing of all currently started jobs, use the jobs command.
These listed jobs can be removed with the disown command.
At the moment, functions cannot be started in the background. Functions
that are stopped and then restarted in the background using the bg
command will not execute correctly.
If the & character is followed by a non-separating character, it is not
interpreted as background operator. Separating characters are
whitespace and the characters ;<>&|.
Functions
Functions are programs written in the fish syntax. They group together
various commands and their arguments using a single name.
For example, here's a simple function to list directories:
function ll
ls -l $argv
end
The first line tells fish to define a function by the name of ll, so it
can be used by simply writing ll on the commandline. The second line
tells fish that the command ls -l $argv should be called when ll is
invoked. $argv is a list variable, which always contains all arguments
sent to the function. In the example above, these are simply passed on
to the ls command. The end on the third line ends the definition.
Calling this as ll /tmp/ will end up running ls -l /tmp/, which will
list the contents of /tmp.
This is a kind of function known as an alias.
Fish's prompt is also defined in a function, called fish_prompt. It is
run when the prompt is about to be displayed and its output forms the
prompt:
function fish_prompt
# A simple prompt. Displays the current directory
# (which fish stores in the $PWD variable)
# and then a user symbol - a '>' for a normal user and a '#' for root.
set -l user_char '>'
if fish_is_root_user
set user_char '#'
end
echo (set_color yellow)$PWD (set_color purple)$user_char
end
To edit a function, you can use funced, and to save a function
funcsave. This will store it in a function file that fish will autoload
when needed.
The functions builtin can show a function's current definition (and
type will also do if given a function).
For more information on functions, see the documentation for the
function builtin.
Defining aliases
One of the most common uses for functions is to slightly alter the
behavior of an already existing command. For example, one might want to
redefine the ls command to display colors. The switch for turning on
colors on GNU systems is --color=auto. An alias around ls might look
like this:
function ls
command ls --color=auto $argv
end
There are a few important things that need to be noted about aliases:
o Always take care to add the $argv variable to the list of parameters
to the wrapped command. This makes sure that if the user specifies
any additional parameters to the function, they are passed on to the
underlying command.
o If the alias has the same name as the aliased command, you need to
prefix the call to the program with command to tell fish that the
function should not call itself, but rather a command with the same
name. If you forget to do so, the function would call itself until
the end of time. Usually fish is smart enough to figure this out and
will refrain from doing so (which is hopefully in your interest).
To easily create a function of this form, you can use the alias
command. Unlike other shells, this just makes functions - fish has no
separate concept of an "alias", we just use the word for a simple
wrapping function like this. alias immediately creates a function.
Consider using alias --save or funcsave to save the created function
into an autoload file instead of recreating the alias each time.
For an alternative, try abbreviations. These are words that are
expanded while you type, instead of being actual functions inside the
shell.
Autoloading functions
Functions can be defined on the commandline or in a configuration file,
but they can also be automatically loaded. This has some advantages:
o An autoloaded function becomes available automatically to all running
shells.
o If the function definition is changed, all running shells will
automatically reload the altered version, after a while.
o Startup time and memory usage is improved, etc.
When fish needs to load a function, it searches through any directories
in the list variable $fish_function_path for a file with a name
consisting of the name of the function plus the suffix .fish and loads
the first it finds.
For example if you try to execute something called banana, fish will go
through all directories in $fish_function_path looking for a file
called banana.fish and load the first one it finds.
By default $fish_function_path contains the following:
o A directory for users to keep their own functions, usually
~/.config/fish/functions (controlled by the XDG_CONFIG_HOME
environment variable).
o A directory for functions for all users on the system, usually
/etc/fish/functions (really $__fish_sysconfdir/functions).
o Directories for other software to put their own functions. These are
in the directories under $__fish_user_data_dir (usually
~/.local/share/fish, controlled by the XDG_DATA_HOME environment
variable) and in the XDG_DATA_DIRS environment variable, in a
subdirectory called fish/vendor_functions.d. The default value for
XDG_DATA_DIRS is usually /usr/share/fish/vendor_functions.d and
/usr/local/share/fish/vendor_functions.d.
o The functions shipped with fish, usually installed in
/usr/share/fish/functions (really $__fish_data_dir/functions).
If you are unsure, your functions probably belong in
~/.config/fish/functions.
As we've explained, autoload files are loaded by name, so, while you
can put multiple functions into one file, the file will only be loaded
automatically once you try to execute the one that shares the name.
Autoloading also won't work for event handlers, since fish cannot know
that a function is supposed to be executed when an event occurs when it
hasn't yet loaded the function. See the event handlers section for more
information.
If a file of the right name doesn't define the function, fish will not
read other autoload files, instead it will go on to try builtins and
finally commands. This allows masking a function defined later in
$fish_function_path, e.g. if your administrator has put something into
/etc/fish/functions that you want to skip.
If you are developing another program and want to install fish
functions for it, install them to the "vendor" functions directory. As
this path varies from system to system, you can use pkgconfig to
discover it with the output of pkg-config --variable functionsdir fish.
Your installation system should support a custom path to override the
pkgconfig path, as other distributors may need to alter it easily.
Comments
Anything after a # until the end of the line is a comment. That means
it's purely for the reader's benefit, fish ignores it.
This is useful to explain what and why you are doing something:
function ls
# The function is called ls,
# so we have to explicitly call `command ls` to avoid calling ourselves.
command ls --color=auto $argv
end
There are no multiline comments. If you want to make a comment span
multiple lines, simply start each line with a #.
Comments can also appear after a line like so:
set -gx EDITOR emacs # I don't like vim.
Conditions
Fish has some builtins that let you execute commands only if a specific
criterion is met: if, switch, and and or, and also the familiar &&/||
syntax.
The if statement
The if statement runs a block of commands if the condition was true.
Like other shells, but unlike typical programming languages you might
know, the condition here is a command. Fish runs it, and if it returns
a true exit status (that's 0), the if-block is run. For example:
if test -e /etc/os-release
cat /etc/os-release
end
This uses the test command to see if the file /etc/os-release exists.
If it does, it runs cat, which prints it on the screen.
Unlike other shells, the condition command just ends after the first
job, there is no then here. Combiners like and and or extend the
condition.
A more complicated example with a command substitution:
if test "$(uname)" = Linux
echo I like penguins
end
Because test can be used for many different tests, it is important to
quote variables and command substitutions. If the $(uname) was not
quoted, and uname printed nothing it would run test = Linux, which is
an error.
if can also take else if clauses with additional conditions and an
else clause that is executed when everything else was false:
if test "$number" -gt 10
echo Your number was greater than 10
else if test "$number" -gt 5
echo Your number was greater than 5
else if test "$number" -gt 1
echo Your number was greater than 1
else
echo Your number was smaller or equal to 1
end
The not keyword can be used to invert the status:
# Just see if the file contains the string "fish" anywhere.
# This executes the `grep` command, which searches for a string,
# and if it finds it returns a status of 0.
# The `not` then turns 0 into 1 or anything else into 0.
# The `-q` switch stops it from printing any matches.
if not grep -q fish myanimals
echo "You don't have fish!"
else
echo "You have fish!"
end
Other things commonly used in if-conditions:
o contains - to see if a list contains a specific element (if contains
-- /usr/bin $PATH)
o string - to e.g. match strings (if string match -q -- '*-' $arg)
o path - to check if paths of some criteria exist (if path is -rf --
~/.config/fish/config.fish)
o type - to see if a command, function or builtin exists (if type -q
git)
The switch statement
The switch command is used to execute one of possibly many blocks of
commands depending on the value of a string. It can take multiple case
blocks that are executed when the string matches. They can take
wildcards. For example:
switch (uname)
case Linux
echo Hi Tux!
case Darwin
echo Hi Hexley!
case DragonFly '*BSD'
echo Hi Beastie! # this also works for FreeBSD and NetBSD
case '*'
echo Hi, stranger!
end
Unlike other shells or programming languages, there is no fallthrough -
the first matching case block is executed and then control jumps out of
the switch.
Combiners (and / or / && / ||)
For simple checks, you can use combiners. and or && run the second
command if the first succeeded, while or or || run it if the first
failed. For example:
# $XDG_CONFIG_HOME is a standard place to store configuration.
# If it's not set applications should use ~/.config.
set -q XDG_CONFIG_HOME; and set -l configdir $XDG_CONFIG_HOME
or set -l configdir ~/.config
Note that combiners are lazy - only the part that is necessary to
determine the final status is run.
Compare:
if sleep 2; and false
echo 'How did I get here? This should be impossible'
end
and:
if false; and sleep 2
echo 'How did I get here? This should be impossible'
end
These do essentially the same thing, but the former takes 2 seconds
longer because the sleep always needs to run.
Or you can have a case where it is necessary to stop early:
if command -sq foo; and foo
If this went on after seeing that the command "foo" doesn't exist, it
would try to run foo and error because it wasn't found!
Combiners really just execute step-by-step, so it isn't recommended to
build longer chains of them because they might do something you don't
want. Consider:
test -e /etc/my.config
or echo "OH NO WE NEED A CONFIG FILE"
and return 1
This will execute return 1 also if the test succeeded. This is because
fish runs test -e /etc/my.config, sets $status to 0, then skips the
echo, keeps $status at 0, and then executes the return 1 because
$status is still 0.
So if you have more complex conditions or want to run multiple things
after something failed, consider using an if. Here that would be:
if not test -e /etc/my.config
echo "OH NO WE NEED A CONFIG FILE"
return 1
end
Loops and blocks
Like most programming language, fish also has the familiar while and
for loops.
while works like a repeated if:
while true
echo Still running
sleep 1
end
will print "Still running" once a second. You can abort it with ctrl-c.
for loops work like in other shells, which is more like python's
for-loops than e.g. C's:
for file in *
echo file: $file
end
will print each file in the current directory. The part after the in is
just a list of arguments, so you can use any expansions there:
set moreanimals bird fox
for animal in {cat,}fish dog $moreanimals
echo I like the $animal
end
If you need a list of numbers, you can use the seq command to create
one:
for i in (seq 1 5)
echo $i
end
break is available to break out of a loop, and continue to jump to the
next iteration.
Input and output redirections (including pipes) can also be applied to
loops:
while read -l line
echo line: $line
end < file
In addition there's a begin block that just groups commands together so
you can redirect to a block or use a new variable scope without any
repetition:
begin
set -l foo bar # this variable will only be available in this block!
end
Parameter expansion
When fish is given a commandline, it expands the parameters before
sending them to the command. There are multiple different kinds of
expansions:
o Wildcards, to create filenames from patterns - *.jpg
o Variable expansion, to use the value of a variable - $HOME
o Command substitution, to use the output of another command - $(cat
/path/to/file)
o Brace expansion, to write lists with common pre- or suffixes in a
shorter way {/usr,}/bin
o Tilde expansion, to turn the ~ at the beginning of paths into the
path to the home directory ~/bin
Parameter expansion is limited to 524288 items. There is a limit to how
many arguments the operating system allows for any command, and 524288
is far above it. This is a measure to stop the shell from hanging doing
useless computation.
Wildcards ("Globbing")
When a parameter includes an unquoted * star (or "asterisk") or a ?
question mark, fish uses it as a wildcard to match files.
o * matches any number of characters (including zero) in a file name,
not including /.
o ** matches any number of characters (including zero), and also
descends into subdirectories. If ** is a segment by itself, that
segment may match zero times, for compatibility with other shells.
o ? can match any single character except /. This is deprecated and can
be disabled via the qmark-noglob feature flag, so ? will just be an
ordinary character.
Wildcard matches are sorted case insensitively. When sorting matches
containing numbers, they are naturally sorted, so that the strings '1'
'5' and '12' would be sorted like 1, 5, 12.
Hidden files (where the name begins with a dot) are not considered when
wildcarding unless the wildcard string has a dot in that place.
Examples:
o a* matches any files beginning with an 'a' in the current directory.
o ** matches any files and directories in the current directory and all
of its subdirectories.
o ~/.* matches all hidden files (also known as "dotfiles") and
directories in your home directory.
For most commands, if any wildcard fails to expand, the command is not
executed, $status is set to nonzero, and a warning is printed. This
behavior is like what bash does with shopt -s failglob. There are
exceptions, namely set and path, overriding variables in overrides,
count and for. Their globs will instead expand to zero arguments (so
the command won't see them at all), like with shopt -s nullglob in
bash.
Examples:
# List the .foo files, or warns if there aren't any.
ls *.foo
# List the .foo files, if any.
set foos *.foo
if count $foos >/dev/null
ls $foos
end
Unlike bash (by default), fish will not pass on the literal glob
character if no match was found, so for a command like apt install that
does the matching itself, you need to add quotes:
apt install "ncurses-*"
Variable expansion
One of the most important expansions in fish is the "variable
expansion". This is the replacing of a dollar sign ($) followed by a
variable name with the _value_ of that variable.
In the simplest case, this is just something like:
echo $HOME
which will replace $HOME with the home directory of the current user,
and pass it to echo, which will then print it.
Some variables like $HOME are already set because fish sets them by
default or because fish's parent process passed them to fish when it
started it. You can define your own variables by setting them with set:
set my_directory /home/cooluser/mystuff
ls $my_directory
# shows the contents of /home/cooluser/mystuff
For more on how setting variables works, see Shell variables and the
following sections.
Sometimes a variable has no value because it is undefined or empty, and
it expands to nothing:
echo $nonexistentvariable
# Prints no output.
To separate a variable name from text you can encase the variable
within double-quotes or braces:
set WORD cat
echo The plural of $WORD is "$WORD"s
# Prints "The plural of cat is cats" because $WORD is set to "cat".
echo The plural of $WORD is {$WORD}s
# ditto
Without the quotes or braces, fish will try to expand a variable called
$WORDs, which may not exist.
The latter syntax {$WORD} is a special case of brace expansion.
If $WORD here is undefined or an empty list, the "s" is not printed.
However, it is printed if $WORD is the empty string (like after set
WORD "").
For more on shell variables, read the Shell variables section.
Quoting variables
Variable expansion also happens in double quoted strings. Inside double
quotes ("these"), variables will always expand to exactly one argument.
If they are empty or undefined, it will result in an empty string. If
they have one element, they'll expand to that element. If they have
more than that, the elements will be joined with spaces, unless the
variable is a path variable - in that case it will use a colon (:)
instead [3].
Fish variables are all lists, and they are split into elements when
they are set - that means it is important to decide whether to use
quotes or not with set:
set foo 1 2 3 # a variable with three elements
rm $foo # runs the equivalent of `rm 1 2 3` - trying to delete three files: 1, 2 and 3.
rm "$foo" # runs `rm '1 2 3'` - trying to delete one file called '1 2 3'
set foo # an empty variable
rm $foo # runs `rm` without arguments
rm "$foo" # runs the equivalent of `rm ''`
set foo "1 2 3"
rm $foo # runs the equivalent of `rm '1 2 3'` - trying to delete one file
rm "$foo" # same thing
This is unlike other shells, which do what is known as "Word
Splitting", where they split the variable when it is used in an
expansion. E.g. in bash:
foo="1 2 3"
rm $foo # runs the equivalent of `rm 1 2 3`
rm "$foo" # runs the equivalent of `rm '1 2 3'`
This is the cause of very common problems with filenames with spaces in
bash scripts.
In fish, unquoted variables will expand to as many arguments as they
have elements. That means an empty list will expand to nothing, a
variable with one element will expand to that element, and a variable
with multiple elements will expand to each of those elements
separately.
If a variable expands to nothing, it will cancel out any other strings
attached to it. See the Combining Lists section for more information.
Most of the time, not quoting a variable is correct. The exception is
when you need to ensure that the variable is passed as one element,
even if it might be unset or have multiple elements. This happens often
with test:
set -l foo one two three
test -n $foo
# prints an error that it got too many arguments, because it was executed like
test -n one two three
test -n "$foo"
# works, because it was executed like
test -n "one two three"
[3] Unlike bash or zsh, which will join with the first character of
$IFS (which usually is space).
Dereferencing variables
The $ symbol can also be used multiple times, as a kind of
"dereference" operator (the * in C or C++), like in the following code:
set foo a b c
set a 10; set b 20; set c 30
for i in (seq (count $$foo))
echo $$foo[$i]
end
# Output is:
# 10
# 20
# 30
$$foo[$i] is "the value of the variable named by $foo[$i]".
This can also be used to give a variable name to a function:
function print_var
for arg in $argv
echo Variable $arg is $$arg
end
end
set -g foo 1 2 3
set -g bar a b c
print_var foo bar
# prints "Variable foo is 1 2 3" and "Variable bar is a b c"
Of course the variable will have to be accessible from the function, so
it needs to be global/universal or exported. It also can't clash with a
variable name used inside the function. So if we had made $foo there a
local variable, or if we had named it "arg" instead, it would not have
worked.
When using this feature together with slices, the slices will be used
from the inside out. $$foo[5] will use the fifth element of $foo as a
variable name, instead of giving the fifth element of all the variables
$foo refers to. That would instead be expressed as $$foo[1..-1][5]
(take all elements of $foo, use them as variable names, then give the
fifth element of those).
Some more examples:
set listone 1 2 3
set listtwo 4 5 6
set var listone listtwo
echo $$var
# Output is 1 2 3 4 5 6
echo $$var[1]
# Output is 1 2 3
echo $$var[2][3]
# $var[1] is listtwo, third element of that is 6, output is 6
echo $$var[..][2]
# The second element of every variable, so output is
# 2 5
Variables as command
Like other shells, you can run the value of a variable as a command.
> set -g EDITOR emacs
> $EDITOR foo # opens emacs, possibly the GUI version
If you want to give the command an argument inside the variable it
needs to be a separate element:
> set EDITOR emacs -nw
> $EDITOR foo # opens emacs in the terminal even if the GUI is installed
> set EDITOR "emacs -nw"
> $EDITOR foo # tries to find a command called "emacs -nw"
Also like other shells, this only works with commands, builtins and
functions - it will not work with keywords because they have
syntactical importance.
For instance set if $if won't allow you to make an if-block, and set
cmd command won't allow you to use the command decorator, but only uses
like $cmd -q foo.
Command substitution
A command substitution is an expansion that uses the output of a
command as the arguments to another. For example:
echo $(pwd)
This executes the pwd command, takes its output (more specifically what
it wrote to the standard output "stdout" stream) and uses it as
arguments to echo. So the inner command (the pwd) is run first and has
to complete before the outer command can even be started.
If the inner command prints multiple lines, fish will use each separate
line as a separate argument to the outer command. Unlike other shells,
the value of $IFS is not used [4], fish splits on newlines.
Command substitutions can also be double-quoted:
echo "$(pwd)"
When using double quotes, the command output is not split up by lines,
but trailing empty lines are still removed.
If the output is piped to string split or string split0 as the last
step, those splits are used as they appear instead of splitting lines.
Fish also allows spelling command substitutions without the dollar,
like echo (pwd). This variant will not be expanded in double-quotes
(echo "(pwd)" will print (pwd)).
The exit status of the last run command substitution is available in
the status variable if the substitution happens in the context of a set
command (so if set -l (something) checks if something returned true).
To use only some lines of the output, refer to slices.
Examples:
# Outputs 'image.png'.
echo (basename image.jpg .jpg).png
# Convert all JPEG files in the current directory to the
# PNG format using the 'convert' program.
for i in *.jpg; convert $i (basename $i .jpg).png; end
# Set the ``data`` variable to the contents of 'data.txt'
# without splitting it into a list.
set data "$(cat data.txt)"
# Set ``$data`` to the contents of data, splitting on NUL-bytes.
set data (cat data | string split0)
Sometimes you want to pass the output of a command to another command
that only accepts files. If it's just one file, you can usually just
pass it via a pipe, like:
grep fish myanimallist1 | wc -l
but if you need multiple or the command doesn't read from standard
input, "process substitution" is useful. Other shells allow this via
foo <(bar) <(baz), and fish uses the psub command:
# Compare just the lines containing "fish" in two files:
diff -u (grep fish myanimallist1 | psub) (grep fish myanimallist2 | psub)
This creates a temporary file, stores the output of the command in that
file and prints the filename, so it is given to the outer command.
Fish has a default limit of 100 MiB on the data it will read in a
command substitution. If that limit is reached the command (all of it,
not just the command substitution - the outer command won't be executed
at all) fails and $status is set to 122. This is so command
substitutions can't cause the system to go out of memory, because
typically your operating system has a much lower limit, so reading more
than that would be useless and harmful. This limit can be adjusted with
the fish_read_limit variable (0 meaning no limit). This limit also
affects the read command.
[4] One exception: Setting $IFS to empty will disable line splitting.
This is deprecated, use string split instead.
Brace expansion
Curly braces can be used to write comma-separated lists. They will be
expanded with each element becoming a new parameter, with the
surrounding string attached. This is useful to save on typing, and to
separate a variable name from surrounding text.
Examples:
> echo input.{c,h,txt}
input.c input.h input.txt
# Move all files with the suffix '.c' or '.h' to the subdirectory src.
> mv *.{c,h} src/
# Make a copy of `file` at `file.bak`.
> cp file{,.bak}
> set -l dogs hot cool cute "good "
> echo {$dogs}dog
hotdog cooldog cutedog good dog
If there is no "," or variable expansion between the curly braces, they
will not be expanded:
# This {} isn't special
> echo foo-{}
foo-{}
# This passes "HEAD@{2}" to git
> git reset --hard HEAD@{2}
> echo {{a,b}}
{a} {b} # because the inner brace pair is expanded, but the outer isn't.
If after expansion there is nothing between the braces, the argument
will be removed (see the Combining Lists section):
> echo foo-{$undefinedvar}
# Output is an empty line, just like a bare `echo`.
If there is nothing between a brace and a comma or two commas, it's
interpreted as an empty element:
> echo {,,/usr}/bin
/bin /bin /usr/bin
To use a "," as an element, quote or escape it.
Combining lists
Fish expands lists like brace expansions:
>_ set -l foo x y z
>_ echo 1$foo
# Any element of $foo is combined with the "1":
1x 1y 1z
>_ echo {good,bad}" apples"
# Any element of the {} is combined with the " apples":
good apples bad apples
# Or we can mix the two:
>_ echo {good,bad}" "$foo
good x bad x good y bad y good z bad z
Any string attached to a list will be concatenated to each element.
Two lists will be expanded in all combinations - every element of the
first with every element of the second:
>_ set -l a x y z; set -l b 1 2 3
>_ echo $a$b # same as {x,y,z}{1,2,3}
x1 y1 z1 x2 y2 z2 x3 y3 z3
A result of this is that, if a list has no elements, this combines the
string with no elements, which means the entire token is removed!
>_ set -l c # <- this list is empty!
>_ echo {$c}word
# Output is an empty line - the "word" part is gone
This can be quite useful. For example, if you want to go through all
the files in all the directories in PATH, use
for file in $PATH/*
Because PATH is a list, this expands to all the files in all the
directories in it. And if there are no directories in PATH, the right
answer here is to expand to no files.
Sometimes this may be unwanted, especially that tokens can disappear
after expansion. In those cases, you should double-quote variables -
echo "$c"word.
This also happens after command substitution. To avoid tokens
disappearing there, make the inner command return a trailing newline,
or double-quote it:
>_ set b 1 2 3
>_ echo (echo x)$b
x1 x2 x3
>_ echo (printf '%s' '')banana
# the printf prints nothing, so this is nothing times "banana",
# which is nothing.
>_ echo (printf '%s\n' '')banana
# the printf prints a newline,
# so the command substitution expands to an empty string,
# so this is `''banana`
banana
>_ echo "$(printf '%s' '')"banana
# quotes mean this is one argument, the banana stays
Slices
Sometimes it's necessary to access only some of the elements of a list
(all fish variables are lists), or some of the lines a command
substitution outputs. Both are possible in fish by writing a set of
indices in brackets, like:
# Make $var a list of four elements
set var one two three four
# Print the second:
echo $var[2]
# prints "two"
# or print the first three:
echo $var[1..3]
# prints "one two three"
In index brackets, fish understands ranges written like a..b ('a' and
'b' being indices). They are expanded into a sequence of indices from a
to b (so a a+1 a+2 ... b), going up if b is larger and going down if a
is larger. Negative indices can also be used - they are taken from the
end of the list, so -1 is the last element, and -2 the one before it.
If an index doesn't exist the range is clamped to the next possible
index.
If a list has 5 elements the indices go from 1 to 5, so a range of
2..16 will only go from element 2 to element 5.
If the end is negative the range always goes up, so 2..-2 will go from
element 2 to 4, and 2..-16 won't go anywhere because there is no way to
go from the second element to one that doesn't exist, while going up.
If the start is negative the range always goes down, so -2..1 will go
from element 4 to 1, and -16..2 won't go anywhere because there is no
way to go from an element that doesn't exist to the second element,
while going down.
A missing starting index in a range defaults to 1. This is allowed if
the range is the first index expression of the sequence. Similarly, a
missing ending index, defaulting to -1 is allowed for the last index in
the sequence.
Multiple ranges are also possible, separated with a space.
Some examples:
echo (seq 10)[1 2 3]
# Prints: 1 2 3
# Limit the command substitution output
echo (seq 10)[2..5]
# Uses elements from 2 to 5
# Output is: 2 3 4 5
echo (seq 10)[7..]
# Prints: 7 8 9 10
# Use overlapping ranges:
echo (seq 10)[2..5 1..3]
# Takes elements from 2 to 5 and then elements from 1 to 3
# Output is: 2 3 4 5 1 2 3
# Reverse output
echo (seq 10)[-1..1]
# Uses elements from the last output line to
# the first one in reverse direction
# Output is: 10 9 8 7 6 5 4 3 2 1
# The command substitution has only one line,
# so these will result in empty output:
echo (echo one)[2..-1]
echo (echo one)[-3..1]
The same works when setting or expanding variables:
# Reverse path variable
set PATH $PATH[-1..1]
# or
set PATH[-1..1] $PATH
# Use only n last items of the PATH
set n -3
echo $PATH[$n..-1]
Variables can be used as indices for expansion of variables, like so:
set index 2
set letters a b c d
echo $letters[$index] # returns 'b'
However using variables as indices for command substitution is
currently not supported, so:
echo (seq 5)[$index] # This won't work
set sequence (seq 5) # It needs to be written on two lines like this.
echo $sequence[$index] # returns '2'
When using indirect variable expansion with multiple $ ($$name), you
have to give all indices up to the variable you want to slice:
> set -l list 1 2 3 4 5
> set -l name list
> echo $$name[1]
1 2 3 4 5
> echo $$name[1..-1][1..3] # or $$name[1][1..3], since $name only has one element.
1 2 3
Home directory expansion
The ~ (tilde) character at the beginning of a parameter, followed by a
username, is expanded into the home directory of the specified user. A
lone ~, or a ~ followed by a slash, is expanded into the home directory
of the process owner:
ls ~/Music # lists my music directory
echo ~root # prints root's home directory, probably "/root"
Combining different expansions
All of the above expansions can be combined. If several expansions
result in more than one parameter, all possible combinations are
created.
When combining multiple parameter expansions, expansions are performed
in the following order:
o Command substitutions
o Variable expansions
o Bracket expansion
o Wildcard expansion
Expansions are performed from right to left, nested bracket expansions
and command substitutions are performed from the inside and out.
Example:
If the current directory contains the files 'foo' and 'bar', the
command echo a(ls){1,2,3} will output abar1 abar2 abar3 afoo1 afoo2
afoo3.
Table Of Operators
Putting it together, here is a quick reference to fish's operators, all
of the special symbols it uses:
+-----------+---------------------+---------------------+
|Symbol | Meaning | Example |
+-----------+---------------------+---------------------+
|$ | Variable expansion | echo $foo |
+-----------+---------------------+---------------------+
|$() and () | Command | cat (grep foo bar) |
| | substitution | or cat $(grep foo |
| | | bar) |
+-----------+---------------------+---------------------+
|< and > | Redirection, like | git shortlog -nse . |
| | command > file | > authors |
+-----------+---------------------+---------------------+
|| | Pipe, connect two | foo | grep bar | |
| | or more commands | grep baz |
+-----------+---------------------+---------------------+
|; | End of the command, | command1; command2 |
| | instead of a | |
| | newline | |
+-----------+---------------------+---------------------+
|& | Backgrounding | sleep 5m & |
+-----------+---------------------+---------------------+
|{} | Brace expansion | ls {/usr,}/bin |
+-----------+---------------------+---------------------+
|&& and || | Combiners | mkdir foo && cd foo |
| | | or rm foo || exit |
+-----------+---------------------+---------------------+
|* and ** | Wildcards | cat *.fish or count |
| | | **.jpg |
+-----------+---------------------+---------------------+
|\\ | Escaping | echo foo\nbar or |
| | | echo \$foo |
+-----------+---------------------+---------------------+
|'' and "" | Quoting | rm "file with |
| | | spaces" or echo |
| | | '$foo' |
+-----------+---------------------+---------------------+
|~ | Home directory | ls ~/ or ls ~root/ |
| | expansion | |
+-----------+---------------------+---------------------+
|# | Comments | echo Hello # this |
| | | isn't printed |
+-----------+---------------------+---------------------+
Shell variables
Variables are a way to save data and pass it around. They can be used
just by the shell, or they can be "exported", so that a copy of the
variable is available to any external command the shell starts. An
exported variable is referred to as an "environment variable".
To set a variable value, use the set command. A variable name can not
be empty and can contain only letters, digits, and underscores. It may
begin and end with any of those characters.
Example:
To set the variable smurf_color to the value blue, use the command set
smurf_color blue.
After a variable has been set, you can use the value of a variable in
the shell through variable expansion.
Example:
set smurf_color blue
echo Smurfs are usually $smurf_color
set pants_color red
echo Papa smurf, who is $smurf_color, wears $pants_color pants
So you set a variable with set, and use it with a $ and the name.
Variable Scope
All variables in fish have a scope. For example they can be global or
local to a function or block:
# This variable is global, we can use it everywhere.
set --global name Patrick
# This variable is local, it will not be visible in a function we call from here.
set --local place "at the Krusty Krab"
function local
# This can find $name, but not $place
echo Hello this is $name $place
# This variable is local, it will not be available
# outside of this function
set --local instrument mayonnaise
echo My favorite instrument is $instrument
# This creates a local $name, and won't touch the global one
set --local name Spongebob
echo My best friend is $name
end
local
# Will print:
# Hello this is Patrick
# My favorite instrument is mayonnaise
# My best friend is Spongebob
echo $name, I am $place and my instrument is $instrument
# Will print:
# Patrick, I am at the Krusty Krab and my instrument is
There are four kinds of variable scopes in fish: universal, global,
function and local variables.
o Universal variables are shared between all fish sessions a user is
running on one computer. They are stored on disk and persist even
after reboot.
o Global variables are specific to the current fish session. They can
be erased by explicitly requesting set -e.
o Function variables are specific to the currently executing function.
They are erased ("go out of scope") when the current function ends.
Outside of a function, they don't go out of scope.
o Local variables are specific to the current block of commands, and
automatically erased when a specific block goes out of scope. A block
of commands is a series of commands that begins with one of the
commands for, while , if, function, begin or switch, and ends with
the command end. Outside of a block, this is the same as the function
scope.
Variables can be explicitly set to be universal with the -U or
--universal switch, global with -g or --global, function-scoped with -f
or --function and local to the current block with -l or --local. The
scoping rules when creating or updating a variable are:
o When a scope is explicitly given, it will be used. If a variable of
the same name exists in a different scope, that variable will not be
changed.
o When no scope is given, but a variable of that name exists, the
variable of the smallest scope will be modified. The scope will not
be changed.
o When no scope is given and no variable of that name exists, the
variable is created in function scope if inside a function, or global
scope if no function is executing.
There can be many variables with the same name, but different scopes.
When you use a variable, the smallest scoped variable of that name will
be used. If a local variable exists, it will be used instead of the
global or universal variable of the same name.
Example:
There are a few possible uses for different scopes.
Typically inside functions you should use local scope:
function something
set -l file /path/to/my/file
if not test -e "$file"
set file /path/to/my/otherfile
end
end
# or
function something
if test -e /path/to/my/file
set -f file /path/to/my/file
else
set -f file /path/to/my/otherfile
end
end
If you want to set something in config.fish, or set something in a
function and have it available for the rest of the session, global
scope is a good choice:
# Don't shorten the working directory in the prompt
set -g fish_prompt_pwd_dir_length 0
# Set my preferred cursor style:
function setcursors
set -g fish_cursor_default block
set -g fish_cursor_insert line
set -g fish_cursor_visual underscore
end
# Set my language
set -gx LANG de_DE.UTF-8
If you want to set some personal customization, universal variables are
nice:
# Typically you'd run this interactively, fish takes care of keeping it.
set -U fish_color_autosuggestion 555
Here is an example of local vs function-scoped variables:
function test-scopes
begin
# This is a nice local scope where all variables will die
set -l pirate 'There be treasure in them thar hills'
set -f captain Space, the final frontier
# If no variable of that name was defined, it is function-local.
set gnu "In the beginning there was nothing, which exploded"
end
# This will not output anything, since the pirate was local
echo $pirate
# This will output the good Captain's speech
# since $captain had function-scope.
echo $captain
# This will output Sir Terry's wisdom.
echo $gnu
end
When a function calls another, local variables aren't visible:
function shiver
set phrase 'Shiver me timbers'
end
function avast
set --local phrase 'Avast, mateys'
# Calling the shiver function here can not
# change any variables in the local scope
# so phrase remains as we set it here.
shiver
echo $phrase
end
avast
# Outputs "Avast, mateys"
When in doubt, use function-scoped variables. When you need to make a
variable accessible everywhere, make it global. When you need to
persistently store configuration, make it universal. When you want to
use a variable only in a short block, make it local.
Overriding variables for a single command
If you want to override a variable for a single command, you can use
"var=val" statements before the command:
# Call git status on another directory
# (can also be done via `git -C somerepo status`)
GIT_DIR=somerepo git status
Unlike other shells, fish will first set the variable and then perform
other expansions on the line, so:
set foo banana
foo=gagaga echo $foo
# prints gagaga, while in other shells it might print "banana"
Multiple elements can be given in a brace expansion:
# Call bash with a reasonable default path.
PATH={/usr,}/{s,}bin bash
Or with a glob:
# Run vlc on all mp3 files in the current directory
# If no file exists it will still be run with no arguments
mp3s=*.mp3 vlc $mp3s
Unlike other shells, this does not inhibit any lookup (aliases or
similar). Calling a command after setting a variable override will
result in the exact same command being run.
This syntax is supported since fish 3.1.
Universal Variables
Universal variables are variables that are shared between all the
user's fish sessions on the computer. Fish stores many of its
configuration options as universal variables. This means that in order
to change fish settings, all you have to do is change the variable
value once, and it will be automatically updated for all sessions, and
preserved across computer reboots and login/logout.
To see universal variables in action, start two fish sessions side by
side, and issue the following command in one of them set fish_color_cwd
blue. Since fish_color_cwd is a universal variable, the color of the
current working directory listing in the prompt will instantly change
to blue on both terminals.
Universal variables are stored in the file .config/fish/fish_variables.
Do not edit this file directly, as your edits may be overwritten. Edit
the variables through fish scripts or by using fish interactively
instead.
Do not append to universal variables in config.fish, because these
variables will then get longer with each new shell instance. Instead,
simply set them once at the command line.
Exporting variables
Variables in fish can be exported, so they will be inherited by any
commands started by fish. In particular, this is necessary for
variables used to configure external commands like PAGER or GOPATH, but
also for variables that contain general system settings like PATH or
LANGUAGE. If an external command needs to know a variable, it needs to
be exported. Exported variables are also often called "environment
variables".
This also applies to fish - when it starts up, it receives environment
variables from its parent (usually the terminal). These typically
include system configuration like PATH and locale variables.
Variables can be explicitly set to be exported with the -x or --export
switch, or not exported with the -u or --unexport switch. The
exporting rules when setting a variable are similar to the scoping
rules for variables - when an option is passed it is respected,
otherwise the variable's existing state is used. If no option is passed
and the variable didn't exist yet it is not exported.
As a naming convention, exported variables are in uppercase and
unexported variables are in lowercase.
For example:
set -gx ANDROID_HOME ~/.android # /opt/android-sdk
set -gx CDPATH . ~ (test -e ~/Videos; and echo ~/Videos)
set -gx EDITOR emacs -nw
set -gx GOPATH ~/dev/go
set -gx GTK2_RC_FILES "$XDG_CONFIG_HOME/gtk-2.0/gtkrc"
set -gx LESSHISTFILE "-"
Note: Exporting is not a scope, but an additional state. It typically
makes sense to make exported variables global as well, but
local-exported variables can be useful if you need something more
specific than Overrides. They are copied to functions so the function
can't alter them outside, and still available to commands. Global
variables are accessible to functions whether they are exported or not.
Lists
Fish can store a list (or an "array" if you wish) of multiple strings
inside of a variable:
> set mylist first second third
> printf '%s\n' $mylist # prints each element on its own line
first
second
third
To access one element of a list, use the index of the element inside of
square brackets, like this:
echo $PATH[3]
List indices start at 1 in fish, not 0 like in other languages. This is
because it requires less subtracting of 1 and many common Unix tools
like seq work better with it (seq 5 prints 1 to 5, not 0 to 5). An
invalid index is silently ignored resulting in no value (not even an
empty string, just no argument at all).
If you don't use any brackets, all the elements of the list will be
passed to the command as separate items. This means you can iterate
over a list with for:
for i in $PATH
echo $i is in the path
end
This goes over every directory in PATH separately and prints a line
saying it is in the path.
To create a variable smurf, containing the items blue and small, simply
write:
set smurf blue small
It is also possible to set or erase individual elements of a list:
# Set smurf to be a list with the elements 'blue' and 'small'
set smurf blue small
# Change the second element of smurf to 'evil'
set smurf[2] evil
# Erase the first element
set -e smurf[1]
# Output 'evil'
echo $smurf
If you specify a negative index when expanding or assigning to a list
variable, the index will be taken from the end of the list. For
example, the index -1 is the last element of the list:
> set fruit apple orange banana
> echo $fruit[-1]
banana
> echo $fruit[-2..-1]
orange
banana
> echo $fruit[-1..1] # reverses the list
banana
orange
apple
As you see, you can use a range of indices, see slices for details.
All lists are one-dimensional and can't contain other lists, although
it is possible to fake nested lists using dereferencing - see variable
expansion.
When a list is exported as an environment variable, it is either space
or colon delimited, depending on whether it is a path variable:
> set -x smurf blue small
> set -x smurf_PATH forest mushroom
> env | grep smurf
smurf=blue small
smurf_PATH=forest:mushroom
Fish automatically creates lists from all environment variables whose
name ends in PATH (like PATH, CDPATH or MANPATH), by splitting them on
colons. Other variables are not automatically split.
Lists can be inspected with the count or the contains commands:
> count $smurf
2
> contains blue $smurf
# blue was found, so it exits with status 0
# (without printing anything)
> echo $status
0
> contains -i blue $smurf
1
A nice thing about lists is that they are passed to commands one
element as one argument, so once you've set your list, you can just
pass it:
set -l grep_args -r "my string"
grep $grep_args . # will run the same as `grep -r "my string"` .
Unlike other shells, fish does not do "word splitting" - elements in a
list stay as they are, even if they contain spaces or tabs.
Argument Handling
An important list is $argv, which contains the arguments to a function
or script. For example:
function myfunction
echo $argv[1]
echo $argv[3]
end
This function takes whatever arguments it gets and prints the first and
third:
> myfunction first second third
first
third
> myfunction apple cucumber banana
apple
banana
That covers the positional arguments, but commandline tools often get
various options and flags, and $argv would contain them intermingled
with the positional arguments. Typical unix argument handling allows
short options (-h, also grouped like in ls -lah), long options (--help)
and allows those options to take arguments (--color=auto or --position
anywhere or complete -C"git ") as well as a -- separator to signal the
end of options. Handling all of these manually is tricky and
error-prone.
A more robust approach to option handling is argparse, which checks the
defined options and puts them into various variables, leaving only the
positional arguments in $argv. Here's a simple example:
function mybetterfunction
# We tell argparse about -h/--help and -s/--second
# - these are short and long forms of the same option.
# The "--" here is mandatory,
# it tells it from where to read the arguments.
argparse h/help s/second -- $argv
# exit if argparse failed because
# it found an option it didn't recognize
# - it will print an error
or return
# If -h or --help is given, we print a little help text and return
if set -ql _flag_help
echo "mybetterfunction [-h|--help] [-s|--second] [ARGUMENT ...]"
return 0
end
# If -s or --second is given, we print the second argument,
# not the first and third.
# (this is also available as _flag_s because of the short version)
if set -ql _flag_second
echo $argv[2]
else
echo $argv[1]
echo $argv[3]
end
end
The options will be removed from $argv, so $argv[2] is the second
positional argument now:
> mybetterfunction first -s second third
second
For more information on argparse, like how to handle option arguments,
see the argparse documentation.
PATH variables
Path variables are a special kind of variable used to support
colon-delimited path lists including PATH, CDPATH, MANPATH, PYTHONPATH,
etc. All variables that end in "PATH" (case-sensitive) become PATH
variables by default.
PATH variables act as normal lists, except they are implicitly joined
and split on colons.
set MYPATH 1 2 3
echo "$MYPATH"
# 1:2:3
set MYPATH "$MYPATH:4:5"
echo $MYPATH
# 1 2 3 4 5
echo "$MYPATH"
# 1:2:3:4:5
Path variables will also be exported in the colon form, so set -x
MYPATH 1 2 3 will have external commands see it as 1:2:3.
> set -gx MYPATH /bin /usr/bin /sbin
> env | grep MYPATH
MYPATH=/bin:/usr/bin:/sbin
This is for compatibility with other tools. Unix doesn't have variables
with multiple elements, the closest thing it has are colon-lists like
PATH. For obvious reasons this means no element can contain a :.
Variables can be marked or unmarked as PATH variables via the --path
and --unpath options to set.
Special variables
You can change the settings of fish by changing the values of certain
variables.
PATH A list of directories in which to search for commands. This is a
common unix variable also used by other tools.
CDPATH A list of directories in which the cd builtin looks for a new
directory.
Locale Variables
The locale variables LANG, LC_ALL, LC_COLLATE, LC_CTYPE,
LC_MESSAGES, LC_MONETARY, LC_NUMERIC, and LANG set the language
option for the shell and subprograms. See the section Locale
variables for more information.
Color variables
A number of variable starting with the prefixes fish_color and
fish_pager_color. See Variables for changing highlighting colors
for more information.
fish_term24bit
If this is set to 1, fish will assume the terminal understands
24-bit RGB color sequences, and won't translate them to the 256
or 16 color palette. This is often detected automatically.
fish_term256
If this is set to 1, fish will assume the terminal understands
256 colors, and won't translate matching colors down to the 16
color palette. This is usually autodetected.
fish_ambiguous_width
controls the computed width of ambiguous-width characters. This
should be set to 1 if your terminal renders these characters as
single-width (typical), or 2 if double-width.
fish_emoji_width
controls whether fish assumes emoji render as 2 cells or 1 cell
wide. This is necessary because the correct value changed from 1
to 2 in Unicode 9, and some terminals may not be aware. Set this
if you see graphical glitching related to emoji (or other
"special" characters). It should usually be auto-detected.
fish_autosuggestion_enabled
controls if Autosuggestions are enabled. Set it to 0 to disable,
anything else to enable. By default they are on.
fish_handle_reflow
determines whether fish should try to repaint the commandline
when the terminal resizes. In terminals that reflow text this
should be disabled. Set it to 1 to enable, anything else to
disable.
fish_key_bindings
the name of the function that sets up the keyboard shortcuts for
the command-line editor.
fish_escape_delay_ms
sets how long fish waits for another key after seeing an escape,
to distinguish pressing the escape key from the start of an
escape sequence. The default is 30ms. Increasing it increases
the latency but allows pressing escape instead of alt for
alt+character bindings. For more information, see the chapter in
the bind documentation.
fish_sequence_key_delay_ms
sets how long fish waits for another key after seeing a key that
is part of a longer sequence, to disambiguate. For instance if
you had bound \cx\ce to open an editor, fish would wait for this
long in milliseconds to see a ctrl-e after a ctrl-x. If the time
elapses, it will handle it as a ctrl-x (by default this would
copy the current commandline to the clipboard). See also Key
sequences.
fish_complete_path
determines where fish looks for completion. When trying to
complete for a command, fish looks for files in the directories
in this variable.
fish_cursor_selection_mode
controls whether the selection is inclusive or exclusive of the
character under the cursor (see Copy and Paste).
fish_function_path
determines where fish looks for functions. When fish autoloads a
function, it will look for files in these directories.
fish_greeting
the greeting message printed on startup. This is printed by a
function of the same name that can be overridden for more
complicated changes (see funced)
fish_history
the current history session name. If set, all subsequent
commands within an interactive fish session will be logged to a
separate file identified by the value of the variable. If unset,
the default session name "fish" is used. If set to an empty
string, history is not saved to disk (but is still available
within the interactive session).
fish_trace
if set and not empty, will cause fish to print commands before
they execute, similar to set -x in bash. The trace is printed to
the path given by the --debug-output option to fish or the
FISH_DEBUG_OUTPUT variable. It goes to stderr by default.
FISH_DEBUG
Controls which debug categories fish enables for output,
analogous to the --debug option.
FISH_DEBUG_OUTPUT
Specifies a file to direct debug output to.
fish_user_paths
a list of directories that are prepended to PATH. This can be a
universal variable.
umask the current file creation mask. The preferred way to change the
umask variable is through the umask function. An attempt to set
umask to an invalid value will always fail.
BROWSER
your preferred web browser. If this variable is set, fish will
use the specified browser instead of the system default browser
to display the fish documentation.
Fish also provides additional information through the values of certain
environment variables. Most of these variables are read-only and their
value can't be changed with set.
_ the name of the currently running command (though this is
deprecated, and the use of status current-command is preferred).
argv a list of arguments to the shell or function. argv is only
defined when inside a function call, or if fish was invoked with
a list of arguments, like fish myscript.fish foo bar. This
variable can be changed.
CMD_DURATION
the runtime of the last command in milliseconds.
COLUMNS and LINES
the current size of the terminal in height and width. These
values are only used by fish if the operating system does not
report the size of the terminal. Both variables must be set in
that case otherwise a default of 80x24 will be used. They are
updated when the window size changes.
fish_kill_signal
the signal that terminated the last foreground job, or 0 if the
job exited normally.
fish_killring
a list of entries in fish's kill ring of cut text.
fish_read_limit
how many bytes fish will process with read or in a command
substitution.
fish_pid
the process ID (PID) of the shell.
history
a list containing the last commands that were entered.
HOME the user's home directory. This variable can be changed.
hostname
the machine's hostname.
IFS the internal field separator that is used for word splitting
with the read builtin. Setting this to the empty string will
also disable line splitting in command substitution. This
variable can be changed.
last_pid
the process ID (PID) of the last background process.
PWD the current working directory.
pipestatus
a list of exit statuses of all processes that made up the last
executed pipe. See exit status.
SHLVL the level of nesting of shells. Fish increments this in
interactive shells, otherwise it simply passes it along.
status the exit status of the last foreground job to exit. If the job
was terminated through a signal, the exit status will be 128
plus the signal number.
status_generation
the "generation" count of $status. This will be incremented only
when the previous command produced an explicit status. (For
example, background jobs will not increment this).
TERM the type of the current terminal. When fish tries to determine
how the terminal works - how many colors it supports, what
sequences it sends for keys and other things - it looks at this
variable and the corresponding information in the terminfo
database (see man terminfo).
Note: Typically this should not be changed as the terminal sets
it to the correct value.
USER the current username. This variable can be changed.
EUID the current effective user id, set by fish at startup. This
variable can be changed.
version
the version of the currently running fish (also available as
FISH_VERSION for backward compatibility).
As a convention, an uppercase name is usually used for exported
variables, while lowercase variables are not exported. (CMD_DURATION is
an exception for historical reasons). This rule is not enforced by
fish, but it is good coding practice to use casing to distinguish
between exported and unexported variables.
Fish also uses some variables internally, their name usually starting
with __fish. These are internal and should not typically be modified
directly.
The status variable
Whenever a process exits, an exit status is returned to the program
that started it (usually the shell). This exit status is an integer
number, which tells the calling application how the execution of the
command went. In general, a zero exit status means that the command
executed without problem, but a non-zero exit status means there was
some form of problem.
Fish stores the exit status of the last process in the last job to exit
in the status variable.
If fish encounters a problem while executing a command, the status
variable may also be set to a specific value:
o 0 is generally the exit status of commands if they successfully
performed the requested operation.
o 1 is generally the exit status of commands if they failed to perform
the requested operation.
o 121 is generally the exit status of commands if they were supplied
with invalid arguments.
o 123 means that the command was not executed because the command name
contained invalid characters.
o 124 means that the command was not executed because none of the
wildcards in the command produced any matches.
o 125 means that while an executable with the specified name was
located, the operating system could not actually execute the command.
o 126 means that while a file with the specified name was located, it
was not executable.
o 127 means that no function, builtin or command with the given name
could be located.
If a process exits through a signal, the exit status will be 128 plus
the number of the signal.
The status can be negated with not (or !), which is useful in a
condition. This turns a status of 0 into 1 and any non-zero status into
0.
There is also $pipestatus, which is a list of all status values of
processes in a pipe. One difference is that not applies to $status, but
not $pipestatus, because it loses information.
For example:
not cat file | grep -q fish
echo status is: $status pipestatus is $pipestatus
Here $status reflects the status of grep, which returns 0 if it found
something, negated with not (so 1 if it found something, 0 otherwise).
$pipestatus reflects the status of cat (which returns non-zero for
example when it couldn't find the file) and grep, without the negation.
So if both cat and grep succeeded, $status would be 1 because of the
not, and $pipestatus would be 0 and 0.
It's possible for the first command to fail while the second succeeds.
One common example is when the second program quits early.
For example, if you have a pipeline like:
cat file1 file2 | head -n 50
This will tell cat to print two files, "file1" and "file2", one after
the other, and the head will then only print the first 50 lines. In
this case you might often see this constellation:
> cat file1 file2 | head -n 50
# 50 lines of output
> echo $pipestatus
141 0
Here, the "141" signifies that cat was killed by signal number 13 (128
+ 13 == 141) - a SIGPIPE. You can also use fish_kill_signal to see the
signal number. This happens because it was still working, and then head
closed the pipe, so cat received a signal that it didn't ignore and so
it died.
Whether cat here will see a SIGPIPE depends on how long the file is and
how much it writes at once, so you might see a pipestatus of "0 0",
depending on the implementation. This is a general unix issue and not
specific to fish. Some shells feature a "pipefail" feature that will
call a pipeline failed if one of the processes in it failed, and this
is a big problem with it.
Locale Variables
The "locale" of a program is its set of language and regional settings
that depend on language and cultural convention. In UNIX, these are
made up of several categories. The categories are:
LANG This is the typical environment variable for specifying a
locale. A user may set this variable to express the language
they speak, their region, and a character encoding. The actual
values are specific to their platform, except for special values
like C or POSIX.
The value of LANG is used for each category unless the variable
for that category was set or LC_ALL is set. So typically you
only need to set LANG.
An example value might be en_US.UTF-8 for the american version
of english and the UTF-8 encoding, or de_AT.UTF-8 for the
austrian version of german and the UTF-8 encoding. Your
operating system might have a locale command that you can call
as locale -a to see a list of defined locales.
A UTF-8 encoding is recommended.
LC_ALL Overrides the LANG environment variable and the values of the
other LC_* variables. If this is set, none of the other
variables are used for anything.
Usually the other variables should be used instead. Use LC_ALL
only when you need to override something.
LC_COLLATE
This determines the rules about equivalence of cases and
alphabetical ordering: collation.
LC_CTYPE
This determines classification rules, like if the type of
character is an alpha, digit, and so on. Most importantly, it
defines the text encoding - which numbers map to which
characters. On modern systems, this should typically be
something ending in "UTF-8".
LC_MESSAGES
LC_MESSAGES determines the language in which messages are
diisplayed.
LC_MONETARY
Determines currency, how it is formatted, and the symbols used.
LC_NUMERIC
Sets the locale for formatting numbers.
LC_TIME
Sets the locale for formatting dates and times.
Builtin commands
Fish includes a number of commands in the shell directly. We call these
"builtins". These include:
o Builtins that manipulate the shell state - cd changes directory, set
sets variables
o Builtins for dealing with data, like string for strings and math for
numbers, count for counting lines or arguments, path for dealing with
path
o status for asking about the shell's status
o printf and echo for creating output
o test for checking conditions
o argparse for parsing function arguments
o source to read a script in the current shell (so changes to variables
stay) and eval to execute a string as script
o random to get random numbers or pick a random element from a list
o read for reading from a pipe or the terminal
For a list of all builtins, use builtin -n.
For a list of all builtins, functions and commands shipped with fish,
see the list of commands. The documentation is also available by using
the --help switch.
Command lookup
When fish is told to run something, it goes through multiple steps to
find it.
If it contains a /, fish tries to execute the given file, from the
current directory on.
If it doesn't contain a /, it could be a function, builtin, or external
command, and so fish goes through the full lookup.
In order:
1. It tries to resolve it as a function.
o If the function is already known, it uses that
o If there is a file of the name with a ".fish" suffix in
fish_function_path, it loads that. (If there is more than one file
only the first is used)
o If the function is now defined it uses that
2. It tries to resolve it as a builtin.
3. It tries to find an executable file in PATH.
o If it finds a file, it tells the kernel to run it.
o If the kernel knows how to run the file (e.g. via a #! line -
#!/bin/sh or #!/usr/bin/python), it does it.
o If the kernel reports that it couldn't run it because of a missing
interpreter, and the file passes a rudimentary check, fish tells
/bin/sh to run it.
If none of these work, fish runs the function fish_command_not_found
and sets status to 127.
You can use type to see how fish resolved something:
> type --short --all echo
echo is a builtin
echo is /usr/bin/echo
Querying for user input
Sometimes, you want to ask the user for input, for instance to confirm
something. This can be done with the read builtin.
Let's make up an example. This function will glob the files in all the
directories it gets as arguments, and if there are more than five it
will ask the user if it is supposed to show them, but only if it is
connected to a terminal:
function show_files
# This will glob on all arguments. Any non-directories will be ignored.
set -l files $argv/*
# If there are more than 5 files
if test (count $files) -gt 5
# and both stdin (for reading input)
# and stdout (for writing the prompt)
# are terminals
and isatty stdin
and isatty stdout
# Keep asking until we get a valid response
while read --nchars 1 -l response --prompt-str="Are you sure? (y/n)"
or return 1 # if the read was aborted with ctrl-c/ctrl-d
switch $response
case y Y
echo Okay
# We break out of the while and go on with the function
break
case n N
# We return from the function without printing
echo Not showing
return 1
case '*'
# We go through the while loop and ask again
echo Not valid input
continue
end
end
end
# And now we print the files
printf '%s\n' $files
end
If you run this as show_files /, it will most likely ask you until you
press Y/y or N/n. If you run this as show_files / | cat, it will print
the files without asking. If you run this as show_files ., it might
just print something without asking because there are fewer than five
files.
Shell variable and function names
The names given to variables and functions (so-called "identifiers")
have to follow certain rules:
o A variable name cannot be empty. It can contain only letters, digits,
and underscores. It may begin and end with any of those characters.
o A function name cannot be empty. It may not begin with a hyphen ("-")
and may not contain a slash ("/"). All other characters, including a
space, are valid. A function name also can't be the same as a
reserved keyword or essential builtin like if or set.
o A bind mode name (e.g., bind -m abc ...) must be a valid variable
name.
Other things have other restrictions. For instance what is allowed for
file names depends on your system, but at the very least they cannot
contain a "/" (because that is the path separator) or NULL byte
(because that is how UNIX ends strings).
Configuration files
When fish is started, it reads and runs its configuration files. Where
these are depends on build configuration and environment variables.
The main file is ~/.config/fish/config.fish (or more precisely
$XDG_CONFIG_HOME/fish/config.fish).
Configuration files are run in the following order:
o Configuration snippets (named *.fish) in the directories:
o $__fish_config_dir/conf.d (by default, ~/.config/fish/conf.d/)
o $__fish_sysconf_dir/conf.d (by default, /etc/fish/conf.d/)
o Directories for others to ship configuration snippets for their
software:
o the directories under $__fish_user_data_dir (usually
~/.local/share/fish, controlled by the XDG_DATA_HOME environment
variable)
o a fish/vendor_conf.d directory in the directories listed in
$XDG_DATA_DIRS (default /usr/share/fish/vendor_conf.d and
/usr/local/share/fish/vendor_conf.d)
These directories are also accessible in $__fish_vendor_confdirs.
Note that changing that in a running fish won't do anything as by
that point the directories have already been read.
If there are multiple files with the same name in these directories,
only the first will be executed. They are executed in order of their
filename, sorted (like globs) in a natural order (i.e. "01" sorts
before "2").
o System-wide configuration files, where administrators can include
initialization for all users on the system - similar to /etc/profile
for POSIX-style shells - in $__fish_sysconf_dir (usually
/etc/fish/config.fish).
o User configuration, usually in ~/.config/fish/config.fish (controlled
by the XDG_CONFIG_HOME environment variable, and accessible as
$__fish_config_dir).
~/.config/fish/config.fish is sourced after the snippets. This is so
you can copy snippets and override some of their behavior.
These files are all executed on the startup of every shell. If you want
to run a command only on starting an interactive shell, use the exit
status of the command status --is-interactive to determine if the shell
is interactive. If you want to run a command only when using a login
shell, use status --is-login instead. This will speed up the starting
of non-interactive or non-login shells.
If you are developing another program, you may want to add
configuration for all users of fish on a system. This is discouraged;
if not carefully written, they may have side-effects or slow the
startup of the shell. Additionally, users of other shells won't benefit
from the fish-specific configuration. However, if they are required,
you can install them to the "vendor" configuration directory. As this
path may vary from system to system, pkg-config should be used to
discover it: pkg-config --variable confdir fish.
For system integration, fish also ships a file called
__fish_build_paths.fish. This can be customized during build, for
instance because your system requires special paths to be used.
Future feature flags
Feature flags are how fish stages changes that might break scripts.
Breaking changes are introduced as opt-in, in a few releases they
become opt-out, and eventually the old behavior is removed.
You can see the current list of features via status features:
> status features
stderr-nocaret on 3.0 ^ no longer redirects stderr
qmark-noglob on 3.0 ? no longer globs
regex-easyesc on 3.1 string replace -r needs fewer \\'s
ampersand-nobg-in-token on 3.4 & only backgrounds if followed by a separating character
remove-percent-self off 4.0 %self is no longer expanded (use $fish_pid)
test-require-arg off 4.0 builtin test requires an argument
keyboard-protocols on 4.0 Use keyboard protocols (kitty, xterm's modifyotherkeys
Here is what they mean:
o stderr-nocaret was introduced in fish 3.0 and cannot be turned off
since fish 3.5. It can still be tested for compatibility, but a
no-stderr-nocaret value will simply be ignored. The flag made ^ an
ordinary character instead of denoting an stderr redirection. Use 2>
instead.
o qmark-noglob was also introduced in fish 3.0 (and made the default in
4.0). It makes ? an ordinary character instead of a single-character
glob. Use a * instead (which will match multiple characters) or find
other ways to match files like find.
o regex-easyesc was introduced in 3.1 (and made the default in 3.5). It
makes it so the replacement expression in string replace -r does one
fewer round of escaping. Before, to escape a backslash you would have
to use string replace -ra '([ab])' '\\\\\\\\$1'. After, just '\\\\$1'
is enough. Check your string replace calls if you use this anywhere.
o ampersand-nobg-in-token was introduced in fish 3.4 (and made the
default in 3.5). It makes it so a & i no longer interpreted as the
backgrounding operator in the middle of a token, so dealing with URLs
becomes easier. Either put spaces or a semicolon after the &. This is
recommended formatting anyway, and fish_indent will have done it for
you already.
o remove-percent-self turns off the special %self expansion. It was
introduced in 4.0. To get fish's pid, you can use the fish_pid
variable.
o test-require-arg removes builtin test's one-argument form (test
"string". It was introduced in 4.0. To test if a string is non-empty,
use test -n "string". If disabled, any call to test that would change
sends a debug message of category "deprecated-test", so starting fish
with fish --debug=deprecated-test can be used to find offending
calls.
o keyboard-protocols lets fish turn on various keyboard protocols
including the kitty keyboard protocol. It was introduced in 4.0 and
is on by default. Disable it with no-keyboard-protocols to work
around bugs in your terminal.
These changes are introduced off by default. They can be enabled on a
per session basis:
> fish --features qmark-noglob,regex-easyesc
or opted into globally for a user:
> set -U fish_features regex-easyesc qmark-noglob
Features will only be set on startup, so this variable will only take
effect if it is universal or exported.
You can also use the version as a group, so 3.0 is equivalent to
"stderr-nocaret" and "qmark-noglob". Instead of a version, the special
group all enables all features.
Prefixing a feature with no- turns it off instead. E.g. to reenable the
? single-character glob:
set -Ua fish_features no-qmark-noglob
Event handlers
When defining a new function in fish, it is possible to make it into an
event handler, i.e. a function that is automatically run when a
specific event takes place. Events that can trigger a handler currently
are:
o When a signal is delivered
o When a job exits
o When the value of a variable is updated
o When the prompt is about to be shown
Example:
To specify a signal handler for the WINCH signal, write:
function my_signal_handler --on-signal WINCH
echo Got WINCH signal!
end
Fish already has the following named events for the --on-event switch:
o fish_prompt is emitted whenever a new fish prompt is about to be
displayed.
o fish_preexec is emitted right before executing an interactive
command. The commandline is passed as the first parameter. Not
emitted if command is empty.
o fish_posterror is emitted right after executing a command with syntax
errors. The commandline is passed as the first parameter.
o fish_postexec is emitted right after executing an interactive
command. The commandline is passed as the first parameter. Not
emitted if command is empty.
o fish_exit is emitted right before fish exits.
o fish_cancel is emitted when a commandline is cleared.
o fish_focus_in is emitted when fish's terminal gains focus.
o fish_focus_out is emitted when fish's terminal loses focus.
Events can be fired with the emit command, and do not have to be
defined before. The names just need to match. For example:
function handler --on-event imdone
echo generator is done $argv
end
function generator
sleep 1
# The "imdone" is the name of the event
# the rest is the arguments to pass to the handler
emit imdone with $argv
end
If there are multiple handlers for an event, they will all be run, but
the order might change between fish releases, so you should not rely on
it.
Please note that event handlers only become active when a function is
loaded, which means you need to otherwise source or execute a function
instead of relying on autoloading. One approach is to put it into your
configuration file.
For more information on how to define new event handlers, see the
documentation for the function command.
Debugging fish scripts
Fish includes basic built-in debugging facilities that allow you to
stop execution of a script at an arbitrary point. When this happens you
are presented with an interactive prompt where you can execute any fish
command to inspect or change state (there are no debug commands as
such). For example, you can check or change the value of any variables
using printf and set. As another example, you can run status
print-stack-trace to see how the current breakpoint was reached. To
resume normal execution of the script, simply type exit or ctrl-d.
To start a debug session simply insert the builtin command breakpoint
at the point in a function or script where you wish to gain control,
then run the function or script. Also, the default action of the TRAP
signal is to call this builtin, meaning a running script can be
actively debugged by sending it the TRAP signal (kill -s TRAP ).
There is limited support for interactively setting or modifying
breakpoints from this debug prompt: it is possible to insert new
breakpoints in (or remove old ones from) other functions by using the
funced function to edit the definition of a function, but it is not
possible to add or remove a breakpoint from the function/script
currently loaded and being executed.
Another way to debug script issues is to set the fish_trace variable,
e.g. fish_trace=1 fish_prompt to see which commands fish executes when
running the fish_prompt function.
Profiling fish scripts
If you specifically want to debug performance issues, fish can be run
with the --profile /path/to/profile.log option to save a profile to the
specified path. This profile log includes a breakdown of how long each
step in the execution took.
For example:
> fish --profile /tmp/sleep.prof -ic 'sleep 3s'
> cat /tmp/sleep.prof
Time Sum Command
3003419 3003419 > sleep 3s
This will show the time for each command itself in the first column,
the time for the command and every subcommand (like any commands inside
of a function or command substitutions) in the second and the command
itself in the third, separated with tabs.
The time is given in microseconds.
To see the slowest commands last, sort -nk2 /path/to/logfile is useful.
For profiling fish's startup there is also --profile-startup
/path/to/logfile.
See fish for more information.
Commands
This is a list of all the commands fish ships with.
Broadly speaking, these fall into a few categories:
Keywords
Core language keywords that make up the syntax, like
o if and else for conditions.
o for and while for loops.
o break and continue to control loops.
o function to define functions.
o return to return a status from a function.
o begin to begin a block and end to end any block (including ifs and
loops).
o and, or and not to combine commands logically.
o switch and case to make multiple blocks depending on the value of a
variable.
o command or builtin to tell fish what sort of thing to execute
o time to time execution
o exec tells fish to replace itself with a command.
o end to end a block
Tools
Builtins to do a task, like
o cd to change the current directory.
o echo or printf to produce output.
o set_color to colorize output.
o set to set, query or erase variables.
o read to read input.
o string for string manipulation.
o path for filtering paths and handling their components.
o math does arithmetic.
o argparse to make arguments easier to handle.
o count to count arguments.
o type to find out what sort of thing (command, builtin or function)
fish would call, or if it exists at all.
o test checks conditions like if a file exists or a string is empty.
o contains to see if a list contains an entry.
o eval and source to run fish code from a string or file.
o status to get shell information, like whether it's interactive or a
login shell, or which file it is currently running.
o abbr manages Abbreviations.
o bind to change bindings.
o complete manages completions.
o commandline to get or change the commandline contents.
o fish_config to easily change fish's configuration, like the prompt or
colorscheme.
o random to generate random numbers or pick from a list.
Known functions
Known functions are a customization point. You can change them to
change how your fish behaves. This includes:
o fish_prompt and fish_right_prompt and fish_mode_prompt to print your
prompt.
o fish_command_not_found to tell fish what to do when a command is not
found.
o fish_title to change the terminal's title.
o fish_greeting to show a greeting when fish starts.
o fish_should_add_to_history to determine if a command should be added
to history
Helper functions
Some helper functions, often to give you information for use in your
prompt:
o fish_git_prompt and fish_hg_prompt to print information about the
current git or mercurial repository.
o fish_vcs_prompt to print information for either.
o fish_svn_prompt to print information about the current svn
repository.
o fish_status_to_signal to give a signal name from a return status.
o prompt_pwd to give the current directory in a nicely formatted and
shortened way.
o prompt_login to describe the current login, with user and hostname,
and to explain if you are in a chroot or connected via ssh.
o prompt_hostname to give the hostname, shortened for use in the
prompt.
o fish_is_root_user to check if the current user is an administrator
user like root.
o fish_add_path to easily add a path to $PATH.
o alias to quickly define wrapper functions ("aliases").
o fish_delta to show what you have changed from the default
configuration.
o export as a compatibility function for other shells.
Helper commands
fish also ships some things as external commands so they can be easily
called from elsewhere.
This includes fish_indent to format fish code and fish_key_reader to
show you what escape sequence a keypress produces.
The full list
And here is the full list:
_ - call fish's translations
Synopsis
_ STRING
Description
_ translates its arguments into the current language, if possible.
It is equivalent to gettext fish STRING, meaning it can only be used to
look up fish's own translations.
It requires fish to be built with gettext support. If that support is
disabled, or there is no translation it will simply echo the argument
back.
The language depends on the current locale, set with LANG and
LC_MESSAGES.
Options
_ takes no options.
Examples
> _ File
Datei
abbr - manage fish abbreviations
Synopsis
abbr --add NAME [--position command | anywhere] [-r | --regex PATTERN] [-c | --command COMMAND]
[--set-cursor[=MARKER]] ([-f | --function FUNCTION] | EXPANSION)
abbr --erase NAME ...
abbr --rename OLD_WORD NEW_WORD
abbr --show
abbr --list
abbr --query NAME ...
Description
abbr manages abbreviations - user-defined words that are replaced with
longer phrases when entered.
NOTE:
Only typed-in commands use abbreviations. Abbreviations are not
expanded in scripts.
For example, a frequently-run command like git checkout can be
abbreviated to gco. After entering gco and pressing space or enter,
the full text git checkout will appear in the command line. To avoid
expanding something that looks like an abbreviation, the default
ctrl-space binding inserts a space without expanding.
An abbreviation may match a literal word, or it may match a pattern
given by a regular expression. When an abbreviation matches a word,
that word is replaced by new text, called its expansion. This expansion
may be a fixed new phrase, or it can be dynamically created via a fish
function. This expansion occurs after pressing space or enter.
Combining these features, it is possible to create custom syntaxes,
where a regular expression recognizes matching tokens, and the
expansion function interprets them. See the Examples section.
Changed in version 3.6.0: Previous versions of this allowed saving
abbreviations in universal variables. That's no longer possible.
Existing variables will still be imported and abbr --erase will also
erase the variables. We recommend adding abbreviations to config.fish
by just adding the abbr --add command. When you run abbr, you will see
output like this
> abbr
abbr -a -- foo bar # imported from a universal variable, see `help abbr`
In that case you should take the part before the # comment and save it
in config.fish, then you can run abbr --erase to remove the universal
variable:
> abbr >> ~/.config/fish/config.fish
> abbr --erase (abbr --list)
Alternatively you can keep them in a separate configuration file by
doing something like the following:
> abbr > ~/.config/fish/conf.d/myabbrs.fish
This will save all your abbreviations in "myabbrs.fish", overwriting
the whole file so it doesn't leave any duplicates, or restore
abbreviations you had erased. Of course any functions will have to be
saved separately, see funcsave.
"add" subcommand
abbr [-a | --add] NAME [--position command | anywhere] [-r | --regex PATTERN]
[-c | --command COMMAND] [--set-cursor[=MARKER]] ([-f | --function FUNCTION] | EXPANSION)
abbr --add creates a new abbreviation. With no other options, the
string NAME is replaced by EXPANSION.
With --position command, the abbreviation will only expand when it is
positioned as a command, not as an argument to another command. With
--position anywhere the abbreviation may expand anywhere in the command
line. The default is command.
With --command COMMAND, the abbreviation will only expand when it is
used as an argument to the given COMMAND. Multiple --command can be
used together, and the abbreviation will expand for each. An empty
COMMAND means it will expand only when there is no command. --command
implies --position anywhere and disallows --position command. Even with
different COMMANDS, the NAME of the abbreviation needs to be unique.
Consider using --regex if you want to expand the same word differently
for multiple commands.
With --regex, the abbreviation matches using the regular expression
given by PATTERN, instead of the literal NAME. The pattern is
interpreted using PCRE2 syntax and must match the entire token. If
multiple abbreviations match the same token, the last abbreviation
added is used.
With --set-cursor=MARKER, the cursor is moved to the first occurrence
of MARKER in the expansion. The MARKER value is erased. The MARKER may
be omitted (i.e. simply --set-cursor), in which case it defaults to %.
With -f FUNCTION or --function FUNCTION, FUNCTION is treated as the
name of a fish function instead of a literal replacement. When the
abbreviation matches, the function will be called with the matching
token as an argument. If the function's exit status is 0 (success), the
token will be replaced by the function's output; otherwise the token
will be left unchanged. No EXPANSION may be given separately.
Examples
abbr --add gco git checkout
Add a new abbreviation where gco will be replaced with git checkout.
abbr -a --position anywhere -- -C --color
Add a new abbreviation where -C will be replaced with --color. The --
allows -C to be treated as the name of the abbreviation, instead of an
option.
abbr -a L --position anywhere --set-cursor "% | less"
Add a new abbreviation where L will be replaced with | less, placing
the cursor before the pipe.
function last_history_item
echo $history[1]
end
abbr -a !! --position anywhere --function last_history_item
This first creates a function last_history_item which outputs the last
entered command. It then adds an abbreviation which replaces !! with
the result of calling this function. Taken together, this is similar to
the !! history expansion feature of bash.
function vim_edit
echo vim $argv
end
abbr -a vim_edit_texts --position command --regex ".+\.txt" --function vim_edit
This first creates a function vim_edit which prepends vim before its
argument. It then adds an abbreviation which matches commands ending in
.txt, and replaces the command with the result of calling this
function. This allows text files to be "executed" as a command to open
them in vim, similar to the "suffix alias" feature in zsh.
abbr 4DIRS --set-cursor=! "$(string join \n -- 'for dir in */' 'cd $dir' '!' 'cd ..' 'end')"
This creates an abbreviation "4DIRS" which expands to a multi-line loop
"template." The template enters each directory and then leaves it. The
cursor is positioned ready to enter the command to run in each
directory, at the location of the !, which is itself erased.
abbr --command git co checkout
Turns "co" as an argument to "git" into "checkout". Multiple commands
are possible, --command={git,hg} would expand "co" to "checkout" for
both git and hg.
Other subcommands
abbr --rename OLD_NAME NEW_NAME
Renames an abbreviation, from OLD_NAME to NEW_NAME
abbr [-s | --show]
Show all abbreviations in a manner suitable for import and export
abbr [-l | --list]
Prints the names of all abbreviation
abbr [-e | --erase] NAME
Erases the abbreviation with the given name
abbr -q or --query [NAME...]
Return 0 (true) if one of the NAME is an abbreviation.
abbr -h or --help
Displays help for the abbr command.
alias - create a function
Synopsis
alias
alias [--save] NAME DEFINITION
alias [--save] NAME=DEFINITION
Description
NOTE: This page documents the fish builtin alias. To see the
documentation on any non-fish versions, use command man alias.
alias is a simple wrapper for the function builtin, which creates a
function wrapping a command. It has similar syntax to POSIX shell
alias. For other uses, it is recommended to define a function.
If you want to ease your interactive use, to save typing, consider
using an abbreviation instead.
fish marks functions that have been created by alias by including the
command used to create them in the function description. You can list
alias-created functions by running alias without arguments. They must
be erased using functions -e.
o NAME is the name of the alias
o DEFINITION is the actual command to execute. alias automatically
appends $argv, so that all parameters used with the alias are passed
to the actual command.
You cannot create an alias to a function with the same name. Note that
spaces need to be escaped in the call to alias just like at the command
line, even inside quoted parts.
The following options are available:
-h or --help
Displays help about using this command.
-s or --save
Saves the function created by the alias into your fish
configuration directory using funcsave.
Example
The following code will create rmi, which runs rm with additional
arguments on every invocation.
alias rmi="rm -i"
# This is equivalent to entering the following function:
function rmi --wraps rm --description 'alias rmi=rm -i'
rm -i $argv
end
alias sometimes requires escaping, as you can see here:
# This needs to have the spaces escaped or "Chrome.app..."
# will be seen as an argument to "/Applications/Google":
alias chrome='/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'
See more
1. The function command this builds on.
2. Functions.
3. Defining aliases.
and - conditionally execute a command
Synopsis
PREVIOUS; and COMMAND
Description
and is used to execute a command if the previous command was successful
(returned a status of 0).
and statements may be used as part of the condition in an while or if
block.
and does not change the current exit status itself, but the command it
runs most likely will. The exit status of the last foreground command
to exit can always be accessed using the $status variable.
The -h or --help option displays help about using this command.
Example
The following code runs the make command to build a program. If the
build succeeds, make's exit status is 0, and the program is installed.
If either step fails, the exit status is 1, and make clean is run,
which removes the files created by the build process.
make; and make install; or make clean
See Also
o or command
o not command
argparse - parse options passed to a fish script or function
Synopsis
argparse [OPTIONS] OPTION_SPEC ... -- [ARG ...]
Description
This command makes it easy for fish scripts and functions to handle
arguments. You pass arguments that define the known options, followed
by a literal --, then the arguments to be parsed (which might also
include a literal --). argparse then sets variables to indicate the
passed options with their values, and sets $argv to the remaining
arguments. See the usage section below.
Each option specification (OPTION_SPEC) is written in the domain
specific language described below. All OPTION_SPECs must appear after
any argparse flags and before the -- that separates them from the
arguments to be parsed.
Each option that is seen in the ARG list will result in variables named
_flag_X, where X is the short flag letter and the long flag name (if
they are defined). For example a --help option could cause argparse to
define one variable called _flag_h and another called _flag_help.
The variables will be set with local scope (i.e., as if the script had
done set -l _flag_X). If the flag is a boolean (that is, it just is
passed or not, it doesn't have a value) the values are the short and
long flags seen. If the option is not a boolean the values will be zero
or more values corresponding to the values collected when the ARG list
is processed. If the flag was not seen the flag variable will not be
set.
Options
The following argparse options are available. They must appear before
all OPTION_SPECs:
-n or --name
The command name for use in error messages. By default the
current function name will be used, or argparse if run outside
of a function.
-x or --exclusive OPTIONS
A comma separated list of options that are mutually exclusive.
You can use this more than once to define multiple sets of
mutually exclusive options. You give either the short or long
version of each option, and you still need to otherwise define
the options.
-N or --min-args NUMBER
The minimum number of acceptable non-option arguments. The
default is zero.
-X or --max-args NUMBER
The maximum number of acceptable non-option arguments. The
default is infinity.
-i or --ignore-unknown
Ignores unknown options, keeping them and their arguments in
$argv instead.
-s or --stop-nonopt
Causes scanning the arguments to stop as soon as the first
non-option argument is seen. Among other things, this is useful
to implement subcommands that have their own options.
-h or --help
Displays help about using this command.
Usage
To use this command, pass the option specifications (OPTION_SPEC), a
mandatory --, and then the arguments to be parsed.
A simple example:
argparse 'h/help' 'n/name=' -- $argv
or return
If $argv is empty then there is nothing to parse and argparse returns
zero to indicate success. If $argv is not empty then it is checked for
flags -h, --help, -n and --name. If they are found they are removed
from the arguments and local variables called _flag_OPTION are set so
the script can determine which options were seen. If $argv doesn't have
any errors, like an unknown option or a missing mandatory value for an
option, then argparse exits with a status of zero. Otherwise it writes
appropriate error messages to stderr and exits with a status of one.
The or return means that the function returns argparse's status if it
failed, so if it goes on argparse succeeded.
To use the flags argparse has extracted:
# Checking for _flag_h and _flag_help is equivalent
# We check if it has been given at least once
if set -ql _flag_h
echo "Usage: my_function [-h | --help] [-n | --name=NAME]" >&2
return 1
end
set -l myname somedefault
set -ql _flag_name[1]
and set myname $_flag_name[-1] # here we use the *last* --name=
Any characters in the flag name that are not valid in a variable name
(like - dashes) will be replaced with underscores.
The -- argument is required. You do not have to include any option
specifications or arguments after the -- but you must include the --.
For example, this is acceptable:
set -l argv foo
argparse 'h/help' 'n/name' -- $argv
argparse --min-args=1 -- $argv
But this is not:
set -l argv
argparse 'h/help' 'n/name' $argv
The first -- seen is what allows the argparse command to reliably
separate the option specifications and options to argparse itself (like
--ignore-unknown) from the command arguments, so it is required.
Option Specifications
Each option specification consists of:
o An optional alphanumeric short flag character, followed by a / if the
short flag can be used by someone invoking your command or, for
backwards compatibility, a - if it should not be exposed as a valid
short flag (in which case it will also not be exposed as a flag
variable).
o An optional long flag name, which if not present the short flag can
be used, and if that is also not present, an error is reported
o Nothing if the flag is a boolean that takes no argument or is an
integer flag, or
o = if it requires a value and only the last instance of the flag
is saved, or
o =? if it takes an optional value and only the last instance of
the flag is saved, or
o =+ if it requires a value and each instance of the flag is
saved.
o Optionally a ! followed by fish script to validate the value.
Typically this will be a function to run. If the exit status is zero
the value for the flag is valid. If non-zero the value is invalid.
Any error messages should be written to stdout (not stderr). See the
section on Flag Value Validation for more information.
See the fish_opt command for a friendlier but more verbose way to
create option specifications.
If a flag is not seen when parsing the arguments then the corresponding
_flag_X var(s) will not be set.
Integer flag
Sometimes commands take numbers directly as options, like foo -55. To
allow this one option spec can have the # modifier so that any integer
will be understood as this flag, and the last number will be given as
its value (as if = was used).
The # must follow the short flag letter (if any), and other modifiers
like = are not allowed, except for - (for backwards compatibility):
m#maximum
This does not read numbers given as +NNN, only those that look like
flags - -NNN.
Note: Optional arguments
An option defined with =? can take optional arguments. Optional
arguments have to be directly attached to the option they belong to.
That means the argument will only be used for the option if you use it
like:
cmd --flag=value
# or
cmd -fvalue
but not if used like:
cmd --flag value
# "value" here will be used as a positional argument
# and "--flag" won't have an argument.
If this weren't the case, using an option without an optional argument
would be difficult if you also wanted to use positional arguments.
For example:
grep --color auto
# Here "auto" will be used as the search string,
# "color" will not have an argument and will fall back to the default,
# which also *happens to be* auto.
grep --color always
# Here grep will still only use color "auto"matically
# and search for the string "always".
This isn't specific to argparse but common to all things using
getopt(3) (if they have optional arguments at all). That grep example
is how GNU grep actually behaves.
Flag Value Validation
Sometimes you need to validate the option values. For example, that it
is a valid integer within a specific range, or an ip address, or
something entirely different. You can always do this after argparse
returns but you can also request that argparse perform the validation
by executing arbitrary fish script. To do so simply append an !
(exclamation-mark) then the fish script to be run. When that code is
executed three vars will be defined:
o _argparse_cmd will be set to the value of the value of the argparse
--name value.
o _flag_name will be set to the short or long flag that being
processed.
o _flag_value will be set to the value associated with the flag being
processed.
These variables are passed to the function as local exported variables.
The script should write any error messages to stdout, not stderr. It
should return a status of zero if the flag value is valid otherwise a
non-zero status to indicate it is invalid.
Fish ships with a _validate_int function that accepts a --min and --max
flag. Let's say your command accepts a -m or --max flag and the minimum
allowable value is zero and the maximum is 5. You would define the
option like this: m/max=!_validate_int --min 0 --max 5. The default if
you just call _validate_int without those flags is to simply check that
the value is a valid integer with no limits on the min or max value
allowed.
Here are some examples of flag validations:
# validate that a path is a directory
argparse 'p/path=!test -d "$_flag_value"' -- --path $__fish_config_dir
# validate that a function does not exist
argparse 'f/func=!not functions -q "$_flag_value"' -- -f alias
# validate that a string matches a regex
argparse 'c/color=!string match -rq \'^#?[0-9a-fA-F]{6}$\' "$_flag_value"' -- -c 'c0ffee'
# validate with a validator function
argparse 'n/num=!_validate_int --min 0 --max 99' -- --num 42
Example OPTION_SPECs
Some OPTION_SPEC examples:
o h/help means that both -h and --help are valid. The flag is a boolean
and can be used more than once. If either flag is used then _flag_h
and _flag_help will be set to however either flag was seen, as many
times as it was seen. So it could be set to -h, -h and --help, and
count $_flag_h would yield "3".
o help means that only --help is valid. The flag is a boolean and can
be used more than once. If it is used then _flag_help will be set as
above. Also h-help (with an arbitrary short letter) for backwards
compatibility.
o longonly= is a flag --longonly that requires an option, there is no
short flag or even short flag variable.
o n/name= means that both -n and --name are valid. It requires a value
and can be used at most once. If the flag is seen then _flag_n and
_flag_name will be set with the single mandatory value associated
with the flag.
o n/name=? means that both -n and --name are valid. It accepts an
optional value and can be used at most once. If the flag is seen then
_flag_n and _flag_name will be set with the value associated with the
flag if one was provided else it will be set with no values.
o name=+ means that only --name is valid. It requires a value and can
be used more than once. If the flag is seen then _flag_name will be
set with the values associated with each occurrence.
o x means that only -x is valid. It is a boolean that can be used more
than once. If it is seen then _flag_x will be set as above.
o x=, x=?, and x=+ are similar to the n/name examples above but there
is no long flag alternative to the short flag -x.
o #max (or #-max) means that flags matching the regex "^--?\d+$" are
valid. When seen they are assigned to the variable _flag_max. This
allows any valid positive or negative integer to be specified by
prefixing it with a single "-". Many commands support this idiom. For
example head -3 /a/file to emit only the first three lines of
/a/file.
o n#max means that flags matching the regex "^--?\d+$" are valid. When
seen they are assigned to the variables _flag_n and _flag_max. This
allows any valid positive or negative integer to be specified by
prefixing it with a single "-". Many commands support this idiom. For
example head -3 /a/file to emit only the first three lines of
/a/file. You can also specify the value using either flag: -n NNN or
--max NNN in this example.
o #longonly causes the last integer option to be stored in
_flag_longonly.
After parsing the arguments the argv variable is set with local scope
to any values not already consumed during flag processing. If there are
no unbound values the variable is set but count $argv will be zero.
If an error occurs during argparse processing it will exit with a
non-zero status and print error messages to stderr.
Examples
A simple use:
argparse h/help -- $argv
or return
if set -q _flag_help
# TODO: Print help here
return 0
end
This just wants one option - -h / --help. Any other option is an error.
If it is given it prints help and exits.
How fish_add_path - add to the path parses its args:
argparse -x g,U -x P,U -x a,p g/global U/universal P/path p/prepend a/append h/help m/move v/verbose n/dry-run -- $argv
There are a variety of boolean flags, all with long and short versions.
A few of these cannot be used together, and that is what the -x flag is
used for. -x g,U means that --global and --universal or their short
equivalents conflict, and if they are used together you get an error.
In this case you only need to give the short or long flag, not the full
option specification.
After this it figures out which variable it should operate on according
to the --path flag:
set -l var fish_user_paths
set -q _flag_path
and set var PATH
# ...
# Check for --dry-run.
# The "-" has been replaced with a "_" because
# it is not valid in a variable name
not set -ql _flag_dry_run
and set $var $result
Limitations
One limitation with --ignore-unknown is that, if an unknown option is
given in a group with known options, the entire group will be kept in
$argv. argparse will not do any permutations here.
For instance:
argparse --ignore-unknown h -- -ho
echo $_flag_h # is -h, because -h was given
echo $argv # is still -ho
This limitation may be lifted in future.
Additionally, it can only parse known options up to the first unknown
option in the group - the unknown option could take options, so it
isn't clear what any character after an unknown option means.
begin - start a new block of code
Synopsis
begin; [COMMANDS ...]; end
Description
begin is used to create a new block of code.
A block allows the introduction of a new variable scope, redirection of
the input or output of a set of commands as a group, or to specify
precedence when using the conditional commands like and.
The block is unconditionally executed. begin; ...; end is equivalent to
if true; ...; end.
begin does not change the current exit status itself. After the block
has completed, $status will be set to the status returned by the most
recent command.
The -h or --help option displays help about using this command.
Example
The following code sets a number of variables inside of a block scope.
Since the variables are set inside the block and have local scope, they
will be automatically deleted when the block ends.
begin
set -l PIRATE Yarrr
...
end
echo $PIRATE
# This will not output anything, since the PIRATE variable
# went out of scope at the end of the block
In the following code, all output is redirected to the file out.html.
begin
echo $xml_header
echo $html_header
if test -e $file
...
end
...
end > out.html
bg - send jobs to background
Synopsis
bg [PID ...]
Description
bg sends jobs to the background, resuming them if they are stopped.
A background job is executed simultaneously with fish, and does not
have access to the keyboard. If no job is specified, the last job to be
used is put in the background. If PID is specified, the jobs containing
the specified process IDs are put in the background.
A PID of the format %n, where n is an integer, will be interpreted as
the PID of job number n. Job numbers can be seen in the output of jobs.
When at least one of the arguments isn't a valid job specifier, bg will
print an error without backgrounding anything.
When all arguments are valid job specifiers, bg will background all
matching jobs that exist.
The -h or --help option displays help about using this command.
Example
The typical use is to run something, stop it with ctrl-z, and then
continue it in the background with bg:
> find / -name "*.js" >/tmp/jsfiles 2>/dev/null # oh no, this takes too long, let's press Ctrl-z!
fish: Job 1, 'find / -name "*.js" >/tmp/jsfil>' has stopped
> bg
Send job 1 'find / -name "*.js" >/tmp/jsfiles 2>/dev/null' to background
> # I can continue using this shell!
> # Eventually:
fish: Job 1, 'find / -name "*.js" >/tmp/jsfil>' has ended
bg 123 456 789 will background the jobs that contain processes 123, 456
and 789.
If only 123 and 789 exist, it will still background them and print an
error about 456.
bg 123 banana or bg banana 123 will complain that "banana" is not a
valid job specifier.
bg %2 will background job 2.
bind - handle fish key bindings
Synopsis
bind [(-M | --mode) MODE] [(-m | --sets-mode) NEW_MODE] [--preset | --user] [-s | --silent] KEYS COMMAND ...
bind [(-M | --mode) MODE] [--preset] [--user] [KEYS]
bind [-a | --all] [--preset] [--user]
bind (-f | --function-names)
bind (-L | --list-modes)
bind (-e | --erase) [(-M | --mode) MODE] [--preset] [--user] [-a | --all] | KEYS ...
Description
bind manages key bindings.
If both KEYS and COMMAND are given, bind adds (or replaces) a binding
in MODE. If only KEYS is given, any existing binding in the given MODE
will be printed.
KEYS is a comma-separated list of key names. Modifier keys can be
specified by prefixing a key name with a combination of ctrl-, alt- and
shift-. For example, pressing w while holding the Alt modifier is
written as alt-w. Key names are case-sensitive; for example alt-W is
the same as alt-shift-w. ctrl-x,ctrl-e would mean pressing ctrl-x
followed by ctrl-e.
Some keys have names, usually because they don't have an obvious
printable character representation. They are:
o the arrow keys up, down, left and right,
o backspace,
o comma (,),
o delete,
o end,
o enter,
o escape,
o f1 through f12.
o home,
o insert,
o minus (-),
o pageup,
o pagedown,
o space and
o tab,
These names are case-sensitive.
An empty value ('') for KEYS designates the generic binding that will
be used if nothing else matches. For most bind modes, it makes sense to
bind this to the self-insert function (i.e. bind '' self-insert). This
will insert any keystrokes that have no bindings otherwise.
Non-printable characters are ignored by the editor, so this will not
result in control sequences being inserted.
To find the name of a key combination you can use fish_key_reader.
COMMAND can be any fish command, but it can also be one of a set of
special input functions. These include functions for moving the cursor,
operating on the kill-ring, performing tab completion, etc. Use bind
--function-names or see below for a list of these input functions.
NOTE:
If a script changes the commandline, it should finish by calling the
repaint special input function.
If no KEYS argument is provided, all bindings (in the given MODE) are
printed. If KEYS is provided but no COMMAND, just the binding matching
that sequence is printed.
Key bindings may use "modes", which mimics vi's modal input behavior.
The default mode is "default". Every key binding applies to a single
mode; you can specify which one with -M MODE. If the key binding should
change the mode, you can specify the new mode with -m NEW_MODE. The
mode can be viewed and changed via the $fish_bind_mode variable. If you
want to change the mode from inside a fish function, use set
fish_bind_mode MODE.
To save custom key bindings, put the bind statements into config.fish.
Alternatively, fish also automatically executes a function called
fish_user_key_bindings if it exists.
Options
The following options are available:
-f or --function-names
Display a list of available input functions
-L or --list-modes
Display a list of defined bind modes
-M MODE or --mode MODE
Specify a bind mode that the bind is used in. Defaults to
"default"
-m NEW_MODE or --sets-mode NEW_MODE
Change the current mode to NEW_MODE after this binding is
executed
-e or --erase
Erase the binding with the given sequence and mode instead of
defining a new one. Multiple sequences can be specified with
this flag. Specifying -a or --all with -M or --mode erases all
binds in the given mode regardless of sequence. Specifying -a
or --all without -M or --mode erases all binds in all modes
regardless of sequence.
-a or --all
See --erase
--preset and --user
Specify if bind should operate on user or preset bindings. User
bindings take precedence over preset bindings when fish looks up
mappings. By default, all bind invocations work on the "user"
level except for listing, which will show both levels. All
invocations except for inserting new bindings can operate on
both levels at the same time (if both --preset and --user are
given). --preset should only be used in full binding sets (like
when working on fish_vi_key_bindings).
-s or --silent
Silences some of the error messages, including for unknown key
names and unbound sequences.
-h or --help
Displays help about using this command.
Special input functions
The following special input functions are available:
and only execute the next function if the previous succeeded (note:
only some functions report success)
accept-autosuggestion
accept the current autosuggestion. Returns false when there was
nothing to accept.
backward-char
move one character to the left. If the completion pager is
active, select the previous completion instead.
backward-char-passive
move one character to the left, but do not trigger any
non-movement-related operations. If the cursor is at the start
of the commandline, does nothing. Does not change the selected
item in the completion pager UI when shown.
backward-bigword
move one whitespace-delimited word to the left
backward-token
move one argument to the left
backward-delete-char
deletes one character of input to the left of the cursor
backward-kill-bigword
move the whitespace-delimited word to the left of the cursor to
the killring
backward-kill-token
move the argument to the left of the cursor to the killring
backward-kill-line
move everything from the beginning of the line to the cursor to
the killring
backward-kill-path-component
move one path component to the left of the cursor to the
killring. A path component is everything likely to belong to a
path component, i.e. not any of the following: /={,}'":@ |;<>&,
plus newlines and tabs.
backward-kill-word
move the word to the left of the cursor to the killring. The
"word" here is everything up to punctuation or whitespace.
backward-word
move one word to the left
beginning-of-buffer
moves to the beginning of the buffer, i.e. the start of the
first line
beginning-of-history
move to the beginning of the history
beginning-of-line
move to the beginning of the line
begin-selection
start selecting text
cancel close the pager if it is open, or undo the most recent
completion if one was just inserted, or otherwise cancel the
current commandline and replace it with a new empty one
cancel-commandline
cancel the current commandline and replace it with a new empty
one, leaving the old one in place with a marker to show that it
was cancelled
capitalize-word
make the current word begin with a capital letter
clear-commandline
empty the entire commandline
clear-screen
clears the screen and redraws the prompt. if the terminal
doesn't support clearing the screen it is the same as repaint.
complete
guess the remainder of the current token
complete-and-search
invoke the searchable pager on completion options (for
convenience, this also moves backwards in the completion pager)
delete-char
delete one character to the right of the cursor
delete-or-exit
delete one character to the right of the cursor, or exit the
shell if the commandline is empty
down-line
move down one line
downcase-word
make the current word lowercase
end-of-buffer
moves to the end of the buffer, i.e. the end of the first line
end-of-history
move to the end of the history
end-of-line
move to the end of the line
end-selection
end selecting text
expand-abbr
expands any abbreviation currently under the cursor
execute
run the current commandline
exit exit the shell
forward-bigword
move one whitespace-delimited word to the right
forward-token
move one argument to the right
forward-char
move one character to the right; or if at the end of the
commandline, accept the current autosuggestion. If the
completion pager is active, select the next completion instead.
forward-char-passive
move one character to the right, but do not trigger any
non-movement-related operations. If the cursor is at the end of
the commandline, does not accept the current autosuggestion (if
any). Does not change the selected item in the completion pager,
if shown.
forward-single-char
move one character to the right; or if at the end of the
commandline, accept a single char from the current
autosuggestion.
forward-word
move one word to the right; or if at the end of the commandline,
accept one word from the current autosuggestion.
history-pager
invoke the searchable pager on history (incremental search); or
if the history pager is already active, search further backwards
in time.
history-pager-delete
permanently delete the current history item, either from the
history pager or from an active up-arrow history search
history-search-backward
search the history for the previous match
history-search-forward
search the history for the next match
history-prefix-search-backward
search the history for the previous prefix match
history-prefix-search-forward
search the history for the next prefix match
history-token-search-backward
search the history for the previous matching argument
history-token-search-forward
search the history for the next matching argument
forward-jump and backward-jump
read another character and jump to its next occurrence
after/before the cursor
forward-jump-till and backward-jump-till
jump to right before the next occurrence
repeat-jump and repeat-jump-reverse
redo the last jump in the same/opposite direction
jump-to-matching-bracket
jump to matching bracket if the character under the cursor is
bracket; otherwise, jump to the next occurrence of any right
bracket after the cursor. The following brackets are
considered: ([{}])
jump-till-matching-bracket
the same as jump-to-matching-bracket but offset cursor to the
right for left bracket, and offset cursor to the left for right
bracket. The offset is applied for both the position we jump
from and position we jump to. In other words, the cursor will
continuously jump inside the brackets but won't reach them by 1
character. The input function is useful to emulate ib vi text
object. The following brackets are considered: ([{}])
kill-bigword
move the next whitespace-delimited word to the killring
kill-token
move the next argument to the killring
kill-line
move everything from the cursor to the end of the line to the
killring
kill-selection
move the selected text to the killring
kill-whole-line
move the line (including the following newline) to the killring.
If the line is the last line, its preceding newline is also
removed
kill-inner-line
move the line (without the following newline) to the killring
kill-word
move the next word to the killring
nextd-or-forward-word
if the commandline is empty, then move forward in the directory
history, otherwise move one word to the right; or if at the end
of the commandline, accept one word from the current
autosuggestion.
or only execute the next function if the previous did not succeed
(note: only some functions report failure)
pager-toggle-search
toggles the search field if the completions pager is visible; or
if used after history-pager, search forwards in time.
prevd-or-backward-word
if the commandline is empty, then move backward in the directory
history, otherwise move one word to the left
repaint
reexecutes the prompt functions and redraws the prompt (also
force-repaint for backwards-compatibility)
repaint-mode
reexecutes the fish_mode_prompt and redraws the prompt. This is
useful for vi mode. If no fish_mode_prompt exists or it prints
nothing, it acts like a normal repaint.
self-insert
inserts the matching sequence into the command line
self-insert-notfirst
inserts the matching sequence into the command line, unless the
cursor is at the beginning
suppress-autosuggestion
remove the current autosuggestion. Returns true if there was a
suggestion to remove.
swap-selection-start-stop
go to the other end of the highlighted text without changing the
selection
transpose-chars
transpose two characters to the left of the cursor
transpose-words
transpose two words to the left of the cursor
togglecase-char
toggle the capitalisation (case) of the character under the
cursor
togglecase-selection
toggle the capitalisation (case) of the selection
insert-line-under
add a new line under the current line
insert-line-over
add a new line over the current line
up-line
move up one line
undo and redo
revert or redo the most recent edits on the command line
upcase-word
make the current word uppercase
yank insert the latest entry of the killring into the buffer
yank-pop
rotate to the previous entry of the killring
Additional functions
The following functions are included as normal functions, but are
particularly useful for input editing:
up-or-search and down-or-search
move the cursor or search the history depending on the cursor
position and current mode
edit_command_buffer
open the visual editor (controlled by the VISUAL or EDITOR
environment variables) with the current command-line contents
fish_clipboard_copy
copy the current selection to the system clipboard
fish_clipboard_paste
paste the current selection from the system clipboard before the
cursor
fish_commandline_append
append the argument to the command-line. If the command-line
already ends with the argument, this removes the suffix instead.
Starts with the last command from history if the command-line is
empty.
fish_commandline_prepend
prepend the argument to the command-line. If the command-line
already starts with the argument, this removes the prefix
instead. Starts with the last command from history if the
command-line is empty.
Examples
Exit the shell when ctrl-d is pressed:
bind ctrl-d 'exit'
Perform a history search when pageup is pressed:
bind pageup history-search-backward
Turn on vi key bindings and rebind ctrl-c to clear the input line:
set -g fish_key_bindings fish_vi_key_bindings
bind -M insert ctrl-c kill-whole-line repaint
Launch git diff and repaint the commandline afterwards when ctrl-g is
pressed:
bind ctrl-g 'git diff' repaint
Terminal Limitations
Unix terminals, like the ones fish operates in, are at heart 70s
technology. They have some limitations that applications running inside
them can't workaround.
For instance, historically the control key modifies a character by
setting the top three bits to 0. This means:
o Many characters + control are indistinguishable from other keys:
ctrl-i is tab, ctrl-j is newline (\n).
o Control and shift don't work simultaneously - ctrl-X is the same as
ctrl-x.
Other keys don't have a direct encoding, and are sent as escape
sequences. For example right (->) usually sends \e\[C.
Some modern terminals support newer encodings for keys, that allow
distinguishing more characters and modifiers, and fish enables as many
of these as it can, automatically.
When in doubt, run fish_key_reader - explore what characters keyboard
keys send. If that tells you that pressing ctrl-i sends tab, your
terminal does not support these better encodings, and so fish is
limited to what it sends.
Key timeout
When you've bound a sequence of multiple characters, there is always
the possibility that fish has only seen a part of it, and then it needs
to disambiguate between the full sequence and part of it.
For example:
bind j,k 'commandline -i foo'
# or `bind jk`
will bind the sequence jk to insert "foo" into the commandline. When
you've only pressed "j", fish doesn't know if it should insert the "j"
(because of the default self-insert), or wait for the "k".
You can enable a timeout for this, by setting the
fish_sequence_key_delay_ms variable to the timeout in milliseconds. If
the timeout elapses, fish will no longer wait for the sequence to be
completed, and do what it can with the characters it already has.
The escape key is a special case, because it can be used standalone as
a real key or as part of a longer escape sequence, like function or
arrow keys. Holding alt and something else also typically sends escape,
for example holding alt+a will send an escape character and then an
"a". So the escape character has its own timeout configured with
fish_escape_delay_ms.
See also Key sequences.
block - temporarily block delivery of events
Synopsis
block [(--local | --global)]
block --erase
Description
block delays delivery of all events triggered by fish or the emit, thus
delaying the execution of any function registered --on-event,
--on-process-exit, --on-job-exit, --on-variable and --on-signal until
after the block is removed.
Event blocks should not be confused with code blocks, which are created
with begin, if, while or for
Without options, block sets up a block that is released automatically
at the end of the current function scope.
The following options are available:
-l or --local
Release the block automatically at the end of the current
innermost code block scope.
-g or --global
Never automatically release the lock.
-e or --erase
Release global block.
-h or --help
Display help about using this command.
Example
# Create a function that listens for events
function --on-event foo foo; echo 'foo fired'; end
# Block the delivery of events
block -g
emit foo
# No output will be produced
block -e
# 'foo fired' will now be printed
Notes
Events are only received from the current fish process as there is no
way to send events from one fish process to another.
break - stop the current inner loop
Synopsis
LOOP_CONSTRUCT
[COMMANDS ...]
break
[COMMANDS ...]
end
Description
break halts a currently running loop (LOOP_CONSTRUCT), such as a for or
while loop. It is usually added inside of a conditional block such as
an if block.
There are no parameters for break.
Example
The following code searches all .c files for "smurf", and halts at the
first occurrence.
for i in *.c
if grep smurf $i
echo Smurfs are present in $i
break
end
end
See Also
o the continue command, to skip the remainder of the current iteration
of the current inner loop
breakpoint - launch debug mode
Synopsis
breakpoint
Description
breakpoint is used to halt a running script and launch an interactive
debugging prompt.
For more details, see Debugging fish scripts in the fish manual.
There are no parameters for breakpoint.
builtin - run a builtin command
Synopsis
builtin [OPTIONS] BUILTINNAME
builtin --query BUILTINNAME ...
builtin --names
Description
builtin forces the shell to use a builtin command named BUILTIN, rather
than a function or external program.
The following options are available:
-n or --names
Lists the names of all defined builtins.
-q or --query BUILTIN
Tests if any of the specified builtins exist. If any exist, it
returns 0, 1 otherwise.
-h or --help
Displays help about using this command.
Example
builtin jobs
# executes the jobs builtin, even if a function named jobs exists
case - conditionally execute a block of commands
Synopsis
switch VALUE
[case [GLOB ...]
[COMMAND ...]]
end
Description
switch executes one of several blocks of commands, depending on whether
a specified value matches one of several values. case is used together
with the switch statement in order to determine which block should be
executed.
Each case command is given one or more parameters. The first case
command with a parameter that matches the string specified in the
switch command will be evaluated. case parameters may contain
wildcards. These need to be escaped or quoted in order to avoid regular
wildcard expansion using filenames.
Note that fish does not fall through on case statements. Only the first
matching case is executed.
Note that command substitutions in a case statement will be evaluated
even if its body is not taken. All substitutions, including command
substitutions, must be performed before the value can be compared
against the parameter.
Example
Say $animal contains the name of an animal. Then this code would
classify it:
switch $animal
case cat
echo evil
case wolf dog human moose dolphin whale
echo mammal
case duck goose albatross
echo bird
case shark trout stingray
echo fish
# Note that the next case has a wildcard which is quoted
case '*'
echo I have no idea what a $animal is
end
If the above code was run with $animal set to whale, the output would
be mammal.
If $animal was set to "banana", it would print "I have no idea what a
banana is".
cd - change directory
Synopsis
cd [DIRECTORY]
Description
NOTE: This page documents the fish builtin cd. To see the
documentation on any non-fish versions, use command man cd.
cd changes the current working directory.
If DIRECTORY is given, it will become the new directory. If no
parameter is given, the HOME environment variable will be used.
If DIRECTORY is a relative path, all the paths in the CDPATH will be
tried as prefixes for it, in addition to PWD. It is recommended to
keep . as the first element of CDPATH, or PWD will be tried last.
Fish will also try to change directory if given a command that looks
like a directory (starting with ., / or ~, or ending with /), without
explicitly requiring cd.
Fish also ships a wrapper function around the builtin cd that
understands cd - as changing to the previous directory. See also
prevd. This wrapper function maintains a history of the 25 most
recently visited directories in the $dirprev and $dirnext global
variables. If you make those universal variables your cd history is
shared among all fish instances.
As a special case, cd . is equivalent to cd $PWD, which is useful in
cases where a mountpoint has been recycled or a directory has been
removed and recreated.
The --help or -h option displays help about using this command, and
does not change the directory.
Examples
cd
# changes the working directory to your home directory.
cd /usr/src/fish-shell
# changes the working directory to /usr/src/fish-shell
See Also
Navigate directories using the directory history or the directory stack
cdh - change to a recently visited directory
Synopsis
cdh [DIRECTORY]
Description
cdh with no arguments presents a list of recently visited directories.
You can then select one of the entries by letter or number. You can
also press tab to use the completion pager to select an item from the
list. If you give it a single argument it is equivalent to cd
DIRECTORY.
Note that the cd command limits directory history to the 25 most
recently visited directories. The history is stored in the dirprev and
dirnext variables, which this command manipulates. If you make those
universal variables, your cd history is shared among all fish
instances.
See Also
o the dirh command to print the directory history
o the prevd command to move backward
o the nextd command to move forward
command - run a program
Synopsis
command [OPTIONS] [COMMANDNAME [ARG ...]]
Description
NOTE: This page documents the fish builtin command. To see the
documentation on any non-fish versions, use command man command.
command forces the shell to execute the program COMMANDNAME and ignore
any functions or builtins with the same name.
In command foo, command is a keyword.
The following options are available:
-a or --all
Prints all COMMAND found in PATH, in the order found.
-q or --query
Return 0 if any of the given commands could be found, 127
otherwise. Don't print anything. For compatibility, this is
also --quiet (deprecated).
-s or --search (or -v)
Prints the external command that would be executed, or prints
nothing if no file with the specified name could be found in
PATH.
-h or --help
Displays help about using this command.
Examples
command ls executes the ls program, even if an ls function also exists.
command -s ls prints the path to the ls program.
command -q git; and command git log runs git log only if git exists.
command -sq git and command -q git and command -vq git return true (0) if a git command could be found and don't print anything.
commandline - set or get the current command line buffer
Synopsis
commandline [OPTIONS] [CMD]
Description
commandline can be used to set or get the current contents of the
command line buffer.
With no parameters, commandline returns the current value of the
command line.
With CMD specified, the command line buffer is erased and replaced with
the contents of CMD.
The following options are available:
-C or --cursor
Set or get the current cursor position, not the contents of the
buffer. If no argument is given, the current cursor position is
printed, otherwise the argument is interpreted as the new cursor
position. If one of the options -j, -p or -t is given, the
position is relative to the respective substring instead of the
entire command line buffer.
-B or --selection-start
Get current position of the selection start in the buffer.
-E or --selection-end
Get current position of the selection end in the buffer.
-f or --function
Causes any additional arguments to be interpreted as input
functions, and puts them into the queue, so that they will be
read before any additional actual key presses are. This option
cannot be combined with any other option. See bind for a list
of input functions.
-h or --help
Displays help about using this command.
The following options change the way commandline updates the command
line buffer:
-a or --append
Do not remove the current commandline, append the specified
string at the end of it.
-i or --insert
Do not remove the current commandline, insert the specified
string at the current cursor position
-r or --replace
Remove the current commandline and replace it with the specified
string (default)
The following options change what part of the commandline is printed or
updated:
-b or --current-buffer
Select the entire commandline, not including any displayed
autosuggestion (default).
-j or --current-job
Select the current job - a job here is one pipeline. Stops at
logical operators or terminators (;, &, and newlines).
-p or --current-process
Select the current process - a process here is one command.
Stops at logical operators, terminators, and pipes.
-s or --current-selection
Selects the current selection
-t or --current-token
Selects the current token
--search-field
Use the pager search field instead of the command line. Returns
false if the search field is not shown.
The following options change the way commandline prints the current
commandline buffer:
-c or --cut-at-cursor
Only print selection up until the current cursor position. If
combined with --tokens-expanded, this will print up until the
last completed token - excluding the token the cursor is in.
This is typically what you would want for instance in
completions. To get both, use both commandline --cut-at-cursor
--tokens-expanded; commandline --cut-at-cursor --current-token,
or commandline -cx; commandline -ct for short.
-x or --tokens-expanded
Perform argument expansion on the selection and print one
argument per line. Command substitutions are not expanded but
forwarded as-is.
--tokens-raw
Print arguments in the selection as they appear on the command
line, one per line.
-o or tokenize
Deprecated; do not use.
If commandline is called during a call to complete a given string using
complete -C STRING, commandline will consider the specified string to
be the current contents of the command line.
The following options output metadata about the commandline state:
-L or --line
If no argument is given, print the line that the cursor is on,
with the topmost line starting at 1. Otherwise, set the cursor
to the given line.
--column
If no argument is given, print the 1-based offset from the start
of the line to the cursor position in Unicode code points.
Otherwise, set the cursor to the given code point offset.
-S or --search-mode
Evaluates to true if the commandline is performing a history
search.
-P or --paging-mode
Evaluates to true if the commandline is showing pager contents,
such as tab completions.
--paging-full-mode
Evaluates to true if the commandline is showing pager contents,
such as tab completions and all lines are shown (no " more
rows" message).
--is-valid
Returns true when the commandline is syntactically valid and
complete. If it is, it would be executed when the execute bind
function is called. If the commandline is incomplete, return 2,
if erroneous, return 1.
--showing-suggestion
Evaluates to true (i.e. returns 0) when the shell is currently
showing an automatic history completion/suggestion, available to
be consumed via one of the forward- bindings. For example, can
be used to determine if moving the cursor to the right when
already at the end of the line would have no effect or if it
would cause a completion to be accepted (note that
forward-char-passive does this automatically).
Example
commandline -j $history[3] replaces the job under the cursor with the
third item from the command line history.
If the commandline contains
>_ echo $flounder >&2 | less; and echo $catfish
(with the cursor on the "o" of "flounder")
The echo $flounder >& is the first process, less the second and and
echo $catfish the third.
echo $flounder >&2 | less is the first job, and echo $catfish the
second.
$flounder is the current token.
The most common use for something like completions is
set -l tokens (commandline -xpc)
which gives the current process (what is being completed), tokenized
into separate entries, up to but excluding the currently being
completed token
If you are then also interested in the in-progress token, add
set -l current (commandline -ct)
Note that this makes it easy to render fish's infix matching moot - if
possible it's best if the completions just print all possibilities and
leave the matching to the current token up to fish's logic.
More examples:
>_ commandline -t
$flounder
>_ commandline -ct
$fl
>_ commandline -b # or just commandline
echo $flounder >&2 | less; and echo $catfish
>_ commandline -p
echo $flounder >&2
>_ commandline -j
echo $flounder >&2 | less
complete - edit command-specific tab-completions
Synopsis
complete ((-c | --command) | (-p | --path)) COMMAND [OPTIONS]
complete (-C | --do-complete) [--escape] STRING
Description
complete defines, removes or lists completions for a command.
For an introduction to writing your own completions, see Writing your
own completions in the fish manual.
The following options are available:
-c or --command COMMAND
Specifies that COMMAND is the name of the command. If there is
no -c or -p, one non-option argument will be used as the
command.
-p or --path COMMAND
Specifies that COMMAND is the absolute path of the command
(optionally containing wildcards).
-e or --erase
Deletes the specified completion.
-s or --short-option SHORT_OPTION
Adds a short option to the completions list.
-l or --long-option LONG_OPTION
Adds a GNU-style long option to the completions list.
-o or --old-option OPTION
Adds an old-style short or long option (see below for details).
-a or --arguments ARGUMENTS
Adds the specified option arguments to the completions list.
-k or --keep-order
Keeps the order of ARGUMENTS instead of sorting alphabetically.
Multiple complete calls with -k result in arguments of the later
ones displayed first.
-f or --no-files
This completion may not be followed by a filename.
-F or --force-files
This completion may be followed by a filename, even if another
applicable complete specified --no-files.
-r or --require-parameter
This completion must have an option argument, i.e. may not be
followed by another option. This means that the next argument
is the argument to the option. If this is not given, the option
argument must be attached like -xFoo or --color=auto.
-x or --exclusive
Short for -r and -f.
-d or --description DESCRIPTION
Add a description for this completion, to be shown in the
completion pager.
-w or --wraps WRAPPED_COMMAND
Causes the specified command to inherit completions from
WRAPPED_COMMAND (see below for details).
-n or --condition CONDITION
This completion should only be used if the CONDITION (a shell
command) returns 0. This makes it possible to specify
completions that should only be used in some cases. If multiple
conditions are specified, fish will try them in the order they
are specified until one fails or all succeeded.
-C or --do-complete STRING
Makes complete try to find all possible completions for the
specified string. If there is no STRING, the current commandline
is used instead.
--escape
When used with -C, escape special characters in completions.
-h or --help
Displays help about using this command.
Command-specific tab-completions in fish are based on the notion of
options and arguments. An option is a parameter which begins with a
hyphen, such as -h, -help or --help. Arguments are parameters that do
not begin with a hyphen. Fish recognizes three styles of options, the
same styles as the GNU getopt library. These styles are:
o Short options, like -a. Short options are a single character long,
are preceded by a single hyphen and can be grouped together (like
-la, which is equivalent to -l -a). Option arguments may be specified
by appending the option with the value (-w32), or, if
--require-parameter is given, in the following parameter (-w 32).
o Old-style options, long like -Wall or -name or even short like -a.
Old-style options can be more than one character long, are preceded
by a single hyphen and may not be grouped together. Option arguments
are specified by default following a space (-foo null) or after =
(-foo=null).
o GNU-style long options, like --colors. GNU-style long options can be
more than one character long, are preceded by two hyphens, and can't
be grouped together. Option arguments may be specified after a =
(--quoting-style=shell), or, if --require-parameter is given, in the
following parameter (--quoting-style shell).
Multiple commands and paths can be given in one call to define the same
completions for multiple commands.
Multiple command switches and wrapped commands can also be given to
define multiple completions in one call.
Invoking complete multiple times for the same command adds the new
definitions on top of any existing completions defined for the command.
When -a or --arguments is specified in conjunction with long, short, or
old-style options, the specified arguments are only completed as
arguments for any of the specified options. If -a or --arguments is
specified without any long, short, or old-style options, the specified
arguments are used when completing non-option arguments to the command
(except when completing an option argument that was specified with -r
or --require-parameter).
Command substitutions found in ARGUMENTS should return a
newline-separated list of arguments, and each argument may optionally
have a tab character followed by the argument description. Description
given this way override a description given with -d or --description.
Descriptions given with --description are also used to group options
given with -s, -o or -l. Options with the same (non-empty) description
will be listed as one candidate, and one of them will be picked. If the
description is empty or no description was given this is skipped.
The -w or --wraps options causes the specified command to inherit
completions from another command, "wrapping" the other command. The
wrapping command can also have additional completions. A command can
wrap multiple commands, and wrapping is transitive: if A wraps B, and B
wraps C, then A automatically inherits all of C's completions. Wrapping
can be removed using the -e or --erase options. Wrapping only works for
completions specified with -c or --command and are ignored when
specifying completions with -p or --path.
When erasing completions, it is possible to either erase all
completions for a specific command by specifying complete -c COMMAND
-e, or by specifying a specific completion option to delete.
When complete is called without anything that would define or erase
completions (options, arguments, wrapping, ...), it shows matching
completions instead. So complete without any arguments shows all loaded
completions, complete -c foo shows all loaded completions for foo.
Since completions are autoloaded, you will have to trigger them first.
Examples
The short-style option -o for the gcc command needs a file argument:
complete -c gcc -s o -r
The short-style option -d for the grep command requires one of read,
skip or recurse:
complete -c grep -s d -x -a "read skip recurse"
The su command takes any username as an argument. Usernames are given
as the first colon-separated field in the file /etc/passwd. This can be
specified as:
complete -x -c su -d "Username" -a "(cat /etc/passwd | cut -d : -f 1)"
The rpm command has several different modes. If the -e or --erase flag
has been specified, rpm should delete one or more packages, in which
case several switches related to deleting packages are valid, like the
nodeps switch.
This can be written as:
complete -c rpm -n "__fish_contains_opt -s e erase" -l nodeps -d "Don't check dependencies"
where __fish_contains_opt is a function that checks the command line
buffer for the presence of a specified set of options.
To implement an alias, use the -w or --wraps option:
complete -c hub -w git
Now hub inherits all of the completions from git. Note this can also be
specified in a function declaration (function thing -w otherthing).
complete -c git
Shows all completions for git.
Any command foo that doesn't support grouping multiple short options in
one string (not supporting -xf as short for -x -f) or a short option
and its value in one string (not supporting -d9 instead of -d 9) should
be specified as a single-character old-style option instead of as a
short-style option; for example, complete -c foo -o s; complete -c foo
-o v would never suggest foo -ov but rather foo -o -v.
contains - test if a word is present in a list
Synopsis
contains [OPTIONS] KEY [VALUES ...]
Description
contains tests whether the set VALUES contains the string KEY. If so,
contains exits with code 0; if not, it exits with code 1.
The following options are available:
-i or --index
Print the index (number of the element in the set) of the first
matching element.
-h or --help
Displays help about using this command.
Note that contains interprets all arguments starting with a - as an
option to contains, until an -- argument is reached.
See the examples below.
Example
If animals is a list of animals, the following will test if animals
contains "cat":
if contains cat $animals
echo Your animal list is evil!
end
This code will add some directories to PATH if they aren't yet
included:
for i in ~/bin /usr/local/bin
if not contains $i $PATH
set PATH $PATH $i
end
end
While this will check if function hasargs is being ran with the -q
option:
function hasargs
if contains -- -q $argv
echo '$argv contains a -q option'
end
end
The -- here stops contains from treating -q to an option to itself.
Instead it treats it as a normal string to check.
continue - skip the remainder of the current iteration of the current inner
loop
Synopsis
LOOP_CONSTRUCT; [COMMANDS ...;] continue; [COMMANDS ...;] end
Description
continue skips the remainder of the current iteration of the current
inner loop, such as a for loop or a while loop. It is usually added
inside of a conditional block such as an if statement or a switch
statement.
Example
The following code removes all tmp files that do not contain the word
smurf.
for i in *.tmp
if grep smurf $i
continue
end
# This "rm" is skipped over if "continue" is executed.
rm $i
# As is this "echo"
echo $i
end
See Also
o the break command, to stop the current inner loop
count - count the number of elements of a list
Synopsis
count STRING1 STRING2 ...
COMMAND | count
count [...] < FILE
Description
count prints the number of arguments that were passed to it, plus the
number of newlines passed to it via stdin. This is usually used to find
out how many elements an environment variable list contains, or how
many lines there are in a text file.
count does not accept any options, not even -h or --help.
count exits with a non-zero exit status if no arguments were passed to
it, and with zero if at least one argument was passed.
Note that, like wc -l, reading from stdin counts newlines, so echo -n
foo | count will print 0.
Example
count $PATH
# Returns the number of directories in the users PATH variable.
count *.txt
# Returns the number of files in the current working directory
# ending with the suffix '.txt'.
git ls-files --others --exclude-standard | count
# Returns the number of untracked files in a git repository
printf '%s\n' foo bar | count baz
# Returns 3 (2 lines from stdin plus 1 argument)
count < /etc/hosts
# Counts the number of entries in the hosts file
dirh - print directory history
Synopsis
dirh
Description
dirh prints the current directory history. The current position in the
history is highlighted using the color defined in the
fish_color_history_current environment variable.
dirh does not accept any parameters.
Note that the cd command limits directory history to the 25 most
recently visited directories. The history is stored in the $dirprev and
$dirnext variables.
See Also
o the cdh command to display a prompt to quickly navigate the history
o the prevd command to move backward
o the nextd command to move forward
dirs - print directory stack
Synopsis
dirs [-c]
Description
dirs prints the current directory stack, as created by pushd and
modified by popd.
The following options are available:
-c: Clear the directory stack instead of printing it.
-h or --help
Displays help about using this command.
dirs does not accept any arguments.
See Also
o the cdh command, which provides a more intuitive way to navigate to
recently visited directories.
disown - remove a process from the list of jobs
Synopsis
disown [PID ...]
Description
disown removes the specified job from the list of jobs. The job itself
continues to exist, but fish does not keep track of it any longer.
This will make fish lose all knowledge of the job, so functions defined
with --on-process-exit or --on-job-exit will no longer fire.
Jobs in the list of jobs are sent a hang-up signal when fish
terminates, which usually causes the job to terminate; disown allows
these processes to continue regardless.
If no process is specified, the most recently-used job is removed (like
bg and fg). If one or more PIDs are specified, jobs with the specified
process IDs are removed from the job list. Invalid jobs are ignored and
a warning is printed.
If a job is stopped, it is sent a signal to continue running, and a
warning is printed. It is not possible to use the bg builtin to
continue a job once it has been disowned.
disown returns 0 if all specified jobs were disowned successfully, and
1 if any problems were encountered.
The --help or -h option displays help about using this command.
Example
firefox &; disown will start the Firefox web browser in the background
and remove it from the job list, meaning it will not be closed when the
fish process is closed.
disown (jobs -p) removes all jobs from the job list without terminating
them.
echo - display a line of text
Synopsis
echo [OPTIONS] [STRING]
Description
NOTE: This page documents the fish builtin echo. To see the
documentation on any non-fish versions, use command man echo.
echo displays STRING of text.
The following options are available:
-n Do not output a newline.
-s Do not separate arguments with spaces.
-E Disable interpretation of backslash escapes (default).
-e Enable interpretation of backslash escapes.
Unlike other shells, this echo accepts -- to signal the end of the
options.
Escape Sequences
If -e is used, the following sequences are recognized:
o \ backslash
o \a alert (BEL)
o \b backspace
o \c produce no further output
o \e escape
o \f form feed
o \n new line
o \r carriage return
o \t horizontal tab
o \v vertical tab
o \0NNN byte with octal value NNN (1 to 3 digits)
o \xHH byte with hexadecimal value HH (1 to 2 digits)
Example
> echo 'Hello World'
Hello World
> echo -e 'Top\nBottom'
Top
Bottom
> echo -- -n
-n
See Also
o the printf command, for more control over output formatting
else - execute command if a condition is not met
Synopsis
if CONDITION; COMMANDS_TRUE ...; [else; COMMANDS_FALSE ...;] end
Description
if will execute the command CONDITION*. If the condition's exit status
is 0, the commands COMMANDS_TRUE will execute. If it is not 0 and else
is given, COMMANDS_FALSE will be executed.
Example
The following code tests whether a file foo.txt exists as a regular
file.
if test -f foo.txt
echo foo.txt exists
else
echo foo.txt does not exist
end
emit - emit a generic event
Synopsis
emit EVENT_NAME [ARGUMENTS ...]
Description
emit emits, or fires, an event. Events are delivered to, or caught by,
special functions called event handlers. The arguments are passed to
the event handlers as function arguments.
The --help or -h option displays help about using this command.
Example
The following code first defines an event handler for the generic event
named 'test_event', and then emits an event of that type.
function event_test --on-event test_event
echo event test: $argv
end
emit test_event something
Notes
Note that events are only sent to the current fish process as there is
no way to send events from one fish process to another.
end - end a block of commands
Synopsis
begin
[COMMANDS ...]
end
function NAME [OPTIONS]; COMMANDS ...; end
if CONDITION; COMMANDS_TRUE ...; [else; COMMANDS_FALSE ...;] end
switch VALUE; [case [WILDCARD ...]; [COMMANDS ...]; ...] end
while CONDITION; COMMANDS ...; end
for VARNAME in [VALUES ...]; COMMANDS ...; end
Description
The end keyword ends a block of commands started by one of the
following commands:
o begin to start a block of commands
o function to define a function
o if, switch to conditionally execute commands
o while, for to perform commands multiple times
The end keyword does not change the current exit status. Instead, the
status after it will be the status returned by the most recent command.
eval - evaluate the specified commands
Synopsis
eval [COMMANDS ...]
Description
eval evaluates the specified parameters as a command. If more than one
parameter is specified, all parameters will be joined using a space
character as a separator.
If the command does not need access to stdin, consider using source
instead.
If no piping or other compound shell constructs are required,
variable-expansion-as-command, as in set cmd ls -la; $cmd, is also an
option.
Example
The following code will call the ls command and truncate each filename
to the first 12 characters.
set cmd ls \| cut -c 1-12
eval $cmd
exec - execute command in current process
Synopsis
exec COMMAND
Description
NOTE: This page documents the fish builtin exec. To see the
documentation on any non-fish versions, use command man exec.
exec replaces the currently running shell with a new command. On
successful completion, exec never returns. exec cannot be used inside a
pipeline.
The --help or -h option displays help about using this command.
Example
exec emacs starts up the emacs text editor, and exits fish. When emacs
exits, the session will terminate.
exit - exit the shell
Synopsis
exit [CODE]
Description
exit is a special builtin that causes the shell to exit. Either 255 or
the CODE supplied is used, whichever is lesser. Otherwise, the exit
status will be that of the last command executed.
If exit is called while sourcing a file (using the source builtin) the
rest of the file will be skipped, but the shell itself will not exit.
The --help or -h option displays help about using this command.
export - compatibility function for exporting variables
Synopsis
export
export NAME=VALUE
Description
export is a function included for compatibility with POSIX shells. In
general, the set builtin should be used instead.
When called without arguments, export prints a list of
currently-exported variables, like set -x.
When called with a NAME=VALUE pair, the variable NAME is set to VALUE
in the global scope, and exported as an environment variable to other
commands.
There are no options available.
Example
The following commands have an identical effect.
set -gx PAGER bat
export PAGER=bat
Note: If you want to add to e.g. $PATH, you need to be careful to
combine the list. Quote it, like so:
export PATH="$PATH:/opt/bin"
Or just use set, which avoids this:
set -gx PATH $PATH /opt/bin
See more
1. The set command.
false - return an unsuccessful result
Synopsis
false
Description
false sets the exit status to 1.
See Also
o true command
o $status variable
fg - bring job to foreground
Synopsis
fg [PID]
Description
The fg builtin brings the specified job to the foreground, resuming it
if it is stopped. While a foreground job is executed, fish is
suspended. If no job is specified, the last job to be used is put in
the foreground. If PID is specified, the job containing a process with
the specified process ID is put in the foreground.
For compatibility with other shells, job expansion syntax is supported
for fg. A PID of the format %1 will foreground job 1. Job numbers can
be seen in the output of jobs.
The --help or -h option displays help about using this command.
Example
fg will put the last job in the foreground.
fg %3 will put job 3 into the foreground.
fish - the friendly interactive shell
Synopsis
fish [OPTIONS] [FILE [ARG ...]]
fish [OPTIONS] [-c COMMAND [ARG ...]]
Description
fish is a command-line shell written mainly with interactive use in
mind. This page briefly describes the options for invoking fish. The
full manual is available in HTML by using the help command from inside
fish, and in the fish-doc(1) man page. The tutorial is available as
HTML via help tutorial or in man fish-tutorial.
The following options are available:
-c or --command=COMMAND
Evaluate the specified commands instead of reading from the
commandline, passing additional positional arguments through
$argv.
-C or --init-command=COMMANDS
Evaluate specified commands after reading the configuration but
before executing command specified by -c or reading interactive
input.
-d or --debug=DEBUG_CATEGORIES
Enables debug output and specify a pattern for matching debug
categories. See Debugging below for details.
-o or --debug-output=DEBUG_FILE
Specifies a file path to receive the debug output, including
categories and fish_trace. The default is standard error.
-i or --interactive
The shell is interactive.
--install[=PATH]
When built as self-installable (via cargo), this will unpack
fish's data files and place them in
~/.local/share/fish/install/. fish will also ask to do this
automatically when run interactively. If PATH is given, fish
will install itself into a relocatable directory tree rooted at
that path. That means it will install the data files to
PATH/share/fish and copy itself to PATH/bin/fish.
-l or --login
Act as if invoked as a login shell.
-N or --no-config
Do not read configuration files.
-n or --no-execute
Do not execute any commands, only perform syntax checking.
-p or --profile=PROFILE_FILE
when fish exits, output timing information on all executed
commands to the specified file. This excludes time spent
starting up and reading the configuration.
--profile-startup=PROFILE_FILE
Will write timing for fish startup to specified file.
-P or --private
Enables private mode: fish will not access old or store new
history.
--print-rusage-self
When fish exits, output stats from getrusage.
--print-debug-categories
Print all debug categories, and then exit.
-v or --version
Print version and exit.
-f or --features=FEATURES
Enables one or more comma-separated feature flags.
The fish exit status is generally the exit status of the last
foreground command.
Debugging
While fish provides extensive support for debugging fish scripts, it is
also possible to debug and instrument its internals. Debugging can be
enabled by passing the --debug option. For example, the following
command turns on debugging for background IO thread events, in addition
to the default categories, i.e. debug, error, warning, and
warning-path:
> fish --debug=iothread
Available categories are listed by fish --print-debug-categories. The
--debug option accepts a comma-separated list of categories, and
supports glob syntax. The following command turns on debugging for
complete, history, history-file, and profile-history, as well as the
default categories:
> fish --debug='complete,*history*'
Debug messages output to stderr by default. Note that if fish_trace is
set, execution tracing also outputs to stderr by default. You can
output to a file using the --debug-output option:
> fish --debug='complete,*history*' --debug-output=/tmp/fish.log --init-command='set fish_trace on'
These options can also be changed via the FISH_DEBUG and
FISH_DEBUG_OUTPUT variables. The categories enabled via --debug are
added to the ones enabled by $FISH_DEBUG, so they can be disabled by
prefixing them with - (reader-*,-ast* enables reader debugging and
disables ast debugging).
The file given in --debug-output takes precedence over the file in
FISH_DEBUG_OUTPUT.
fish_add_path - add to the path
Synopsis
fish_add_path path ...
fish_add_path [(-g | --global) | (-U | --universal) | (-P | --path)] [(-m | --move)] [(-a | --append) | (-p | --prepend)] [(-v | --verbose) | (-n | --dry-run)] PATHS ...
Description
fish_add_path is a simple way to add more directories to fish's PATH.
It does this by adding the directories either to fish_user_paths or
directly to PATH (if the --path switch is given).
It is (by default) safe to use fish_add_path in config.fish, or it can
be used once, interactively, and the paths will stay in future because
of universal variables. This is a "do what I mean" style command - it
tries to do the right thing by default, and follow your lead on what
you have already set up (e.g. by using a global fish_user_paths if you
have that already). If you need more control, consider modifying the
variable yourself.
Directories are normalized with realpath. Trailing slashes are ignored
and relative paths are made absolute (but symlinks are not resolved).
If a directory is already included, it is not added again and stays in
the same place unless the --move switch is given.
Directories are added in the order they are given, and they are
prepended to the path unless --append is given. If $fish_user_paths is
used, that means they are last in $fish_user_paths, which is itself
prepended to PATH, so they still stay ahead of the system paths. If the
--path option is used, the paths are appended/prepended to PATH
directly, so this doesn't happen.
With --path, because PATH must be a global variable instead of a
universal one, the changes won't persist, so those calls need to be
stored in config.fish. This also applies to fish_user_paths if you make
it global (for instance by passing --global).
If no directory is new, the variable (fish_user_paths or PATH) is not
set again or otherwise modified, so variable handlers are not
triggered.
If an argument is not an existing directory, fish_add_path ignores it.
Options
-a or --append
Add directories to the end of the variable.
-p or --prepend
Add directories to the front of the variable (this is the
default).
-g or --global
Use a global fish_user_paths.
-U or --universal
Use a universal fish_user_paths - this is the default if it
doesn't already exist.
-P or --path
Manipulate PATH directly.
-m or --move
Move already-included directories to the place they would be
added - by default they would be left in place and not added
again.
-v or --verbose
Print the set command used, and some more warnings, like when a
path is skipped because it doesn't exist or is not a directory.
Verbose mode is automatically enabled when fish_add_path is used
interactively and the output goes to the terminal.
-n or --dry-run
Print the set command that would be used without executing it.
-h or --help
Displays help about using this command.
If --move is used, it may of course lead to the path swapping order, so
you should be careful doing that in config.fish.
Example
# I just installed mycoolthing and need to add it to the path to use it.
# It is at /opt/mycoolthing/bin/mycoolthing,
# so let's add the directory: /opt/mycoolthing/bin.
> fish_add_path /opt/mycoolthing/bin
# I want my ~/.local/bin to be checked first,
# even if it was already added.
> fish_add_path -m ~/.local/bin
# I prefer using a global fish_user_paths
# This isn't saved automatically, I need to add this to config.fish
# if I want it to stay.
> fish_add_path -g ~/.local/bin ~/.otherbin /usr/local/sbin
# I want to append to the entire $PATH because this directory contains fallbacks
# This needs --path/-P because otherwise it appends to $fish_user_paths,
# which is added to the front of $PATH.
> fish_add_path --append --path /opt/fallback/bin
# I want to add the bin/ directory of my current $PWD (say /home/nemo/)
# -v/--verbose shows what fish_add_path did.
> fish_add_path -v bin/
set fish_user_paths /home/nemo/bin /usr/bin /home/nemo/.local/bin
# I have installed ruby via homebrew
> fish_add_path /usr/local/opt/ruby/bin
fish_breakpoint_prompt - define the prompt when stopped at a breakpoint
Synopsis
fish_breakpoint_prompt
function fish_breakpoint_prompt
...
end
Description
fish_breakpoint_prompt is the prompt function when asking for input in
response to a breakpoint command.
The exit status of commands within fish_breakpoint_prompt will not
modify the value of $status outside of the fish_breakpoint_prompt
function.
fish ships with a default version of this function that displays the
function name and line number of the current execution context.
Example
A simple prompt that is a simplified version of the default debugging
prompt:
function fish_breakpoint_prompt -d "Write out the debug prompt"
set -l function (status current-function)
set -l line (status current-line-number)
set -l prompt "$function:$line >"
echo -ns (set_color $fish_color_status) "BP $prompt" (set_color normal) ' '
end
fish_clipboard_copy - copy text to the system's clipboard
Synopsis
fish_clipboard_copy
foo | fish_clipboard_copy
Description
The fish_clipboard_copy function copies text to the system clipboard.
If stdin is not a terminal (see isatty), it will read all input from
there and copy it. If it is, it will use the current commandline, or
the current selection if there is one.
It is bound to ctrl-x by default.
fish_clipboard_copy works by calling a system-specific backend. If it
doesn't appear to work you may need to install yours.
Currently supported are:
o pbcopy
o wl-copy using wayland
o xsel and xclip for X11
o clip.exe on Windows.
See also
o fish_clipboard_paste - get text from the system's clipboard which
does the inverse.
fish_clipboard_paste - get text from the system's clipboard
Synopsis
fish_clipboard_paste
fish_clipboard_paste | foo
Description
The fish_clipboard_paste function copies text from the system
clipboard.
If its stdout is not a terminal (see isatty), it will output everything
there, as-is, without any additional newlines. If it is, it will put
the text in the commandline instead.
If it outputs to the commandline, it will automatically escape the
output if the cursor is currently inside single-quotes so it is
suitable for single-quotes (meaning it escapes ' and \\).
It is bound to ctrl-v by default.
fish_clipboard_paste works by calling a system-specific backend. If it
doesn't appear to work you may need to install yours.
Currently supported are:
o pbpaste
o wl-paste using wayland
o xsel and xclip for X11
o powershell.exe on Windows (this backend has encoding limitations and
uses windows line endings that fish_clipboard_paste undoes)
See also
o fish_clipboard_copy - copy text to the system's clipboard which does
the inverse.
fish_command_not_found - what to do when a command wasn't found
Synopsis
function fish_command_not_found
...
end
Description
When fish tries to execute a command and can't find it, it invokes this
function.
It can print a message to tell you about it, and it often also checks
for a missing package that would include the command.
Fish ships multiple handlers for various operating systems and chooses
from them when this function is loaded, or you can define your own.
It receives the full commandline as one argument per token, so $argv[1]
contains the missing command.
When you leave fish_command_not_found undefined (e.g. by adding an
empty function file) or explicitly call
__fish_default_command_not_found_handler, fish will just print a simple
error.
Example
A simple handler:
function fish_command_not_found
echo Did not find command $argv[1]
end
> flounder
Did not find command flounder
Or the handler for OpenSUSE's command-not-found:
function fish_command_not_found
/usr/bin/command-not-found $argv[1]
end
Or the simple default handler:
function fish_command_not_found
__fish_default_command_not_found_handler $argv
end
Backwards compatibility
This command was introduced in fish 3.2.0. Previous versions of fish
used the "fish_command_not_found" event instead.
To define a handler that works in older versions of fish as well,
define it the old way:
function __fish_command_not_found_handler --on-event fish_command_not_found
echo COMMAND WAS NOT FOUND MY FRIEND $argv[1]
end
in which case fish will define a fish_command_not_found that calls it,
or define a wrapper:
function fish_command_not_found
echo "G'day mate, could not find your command: $argv"
end
function __fish_command_not_found_handler --on-event fish_command_not_found
fish_command_not_found $argv
end
fish_config - start the web-based configuration interface
Synopsis
fish_config [browse]
fish_config prompt (choose | list | save | show)
fish_config theme (choose | demo | dump | list | save | show)
Description
fish_config is used to configure fish.
Without arguments or with the browse command it starts the web-based
configuration interface. The web interface allows you to view your
functions, variables and history, and to make changes to your prompt
and color configuration. It starts a local web server and opens a
browser window. When you are finished, close the browser window and
press the Enter key to terminate the configuration session.
If the BROWSER environment variable is set, it will be used as the name
of the web browser to open instead of the system default.
With the prompt command fish_config can be used to view and choose a
prompt from fish's sample prompts inside the terminal directly.
Available subcommands for the prompt command:
o choose loads a sample prompt in the current session.
o list lists the names of the available sample prompts.
o save saves the current prompt to a file (via funcsave).
o show shows what the given sample prompts (or all) would look like.
With the theme command fish_config can be used to view and choose a
theme (meaning a color scheme) inside the terminal.
Available subcommands for the theme command:
o choose loads a sample theme in the current session.
o demo displays some sample text in the current theme.
o dump prints the current theme in a loadable format.
o list lists the names of the available sample themes.
o save saves the given theme to universal variables.
o show shows what the given sample theme (or all) would look like.
The -h or --help option displays help about using this command.
Theme Files
fish_config theme and the theme selector in the web config tool load
their themes from theme files. These are stored in the fish
configuration directory, typically ~/.config/fish/themes, with a .theme
ending.
You can add your own theme by adding a file in that directory.
To get started quickly:
fish_config theme dump > ~/.config/fish/themes/my.theme
which will save your current theme in .theme format.
The format looks like this:
# name: 'Cool Beans'
# preferred_background: black
fish_color_autosuggestion 666
fish_color_cancel -r
fish_color_command normal
fish_color_comment '888' '--italics'
fish_color_cwd 0A0
fish_color_cwd_root A00
fish_color_end 009900
The two comments at the beginning are the name and background that the
web config tool shows.
The other lines are just like set variable value, except that no
expansions are allowed. Quotes are, but aren't necessary.
Any color variable fish knows about that the theme doesn't set will be
set to empty when it is loaded, so the old theme is completely
overwritten.
Other than that, .theme files can contain any variable with a name that
matches the regular expression '^fish_(?:pager_)?color.*$' - starts
with fish_, an optional pager_, then color and then anything.
Example
fish_config or fish_config browse opens a new web browser window and
allows you to configure certain fish settings.
fish_config prompt show demos the available sample prompts.
fish_config prompt choose disco makes the disco prompt the prompt for
the current session. This can also be used in config.fish to set the
prompt.
fish_config prompt save saves the current prompt to an autoloaded file.
fish_config prompt save default chooses the default prompt and saves
it.
fish_default_key_bindings - set emacs key bindings for fish
Synopsis
fish_default_key_bindings
Description
fish_default_key_bindings sets the emacs key bindings for fish shell.
Some of the Emacs key bindings are defined here.
There are no parameters for fish_default_key_bindings.
Examples
To start using emacs key bindings:
fish_default_key_bindings
fish_delta - compare functions and completions to the default
Synopsis
fish_delta name ...
fish_delta [-f | --no-functions] [-c | --no-completions] [-C | --no-config] [-d | --no-diff] [-n | --new] [-V | --vendor=]
fish_delta [-h | --help]
Description
The fish_delta function tells you, at a glance, which of your functions
and completions differ from the set that fish ships.
It does this by going through the relevant variables
(fish_function_path for functions and fish_complete_path for
completions) and comparing the files against fish's default
directories.
If any names are given, it will only compare files by those names (plus
a ".fish" extension).
By default, it will also use diff to display the difference between the
files. If diff is unavailable, it will skip it, but in that case it
also cannot figure out if the files really differ.
The exit status is 1 if there was a difference and 2 for other errors,
otherwise 0.
Options
The following options are available:
-f or --no-functions
Stops checking functions
-c or --no-completions
Stops checking completions
-C or --no-config
Stops checking configuration files like config.fish or snippets
in the conf.d directories.
-d or --no-diff
Removes the diff display (this happens automatically if diff
can't be found)
-n or --new
Also prints new files (i.e. those that can't be found in fish's
default directories).
-Vvalue or --vendor=value
Determines how the vendor directories are counted. Valid values
are:
o "default" - counts vendor files as belonging to the defaults.
Any changes in other directories will be counted as changes
over them. This is the default.
o "user" - counts vendor files as belonging to the user files.
Any changes in them will be counted as new or changed files.
o "ignore" - ignores vendor directories. Files of the same name
will be counted as "new" if no file of the same name in fish's
default directories exists.
-h or --help
Prints fish_delta's help (this).
Example
Running just:
fish_delta
will give you a list of all your changed functions and completions,
including diffs (if you have the diff command).
It might look like this:
> fish_delta
New: /home/alfa/.config/fish/functions/battery.fish
Changed: /home/alfa/.config/fish/test/completions/cargo.fish
--- /home/alfa/.config/fish/test/completions/cargo.fish 2022-09-02 12:57:55.579229959 +0200
+++ /usr/share/fish/completions/cargo.fish 2022-09-25 17:51:53.000000000 +0200
# the output of `diff` follows
The options are there to select which parts of the output you want.
With --no-completions you can compare just functions, and with
--no-diff you can turn off the diff display.
To only compare your fish_git_prompt, you might use:
fish_delta --no-completions fish_git_prompt
which will only compare files called "fish_git_prompt.fish".
fish_git_prompt - output git information for use in a prompt
Synopsis
fish_git_prompt
function fish_prompt
printf '%s' $PWD (fish_git_prompt) ' $ '
end
Description
The fish_git_prompt function displays information about the current git
repository, if any.
Git must be installed.
There are numerous customization options, which can be controlled with
git options or fish variables. git options, where available, take
precedence over the fish variable with the same function. git options
can be set on a per-repository or global basis. git options can be set
with the git config command, while fish variables can be set as usual
with the set command.
Boolean options (those which enable or disable something) understand
"1", "yes" or "true" to mean true and every other value to mean false.
o $__fish_git_prompt_show_informative_status or the git option
bash.showInformativeStatus can be set to 1, true or yes to enable the
"informative" display, which will show a large amount of information
- the number of dirty files, unpushed/unpulled commits, and more. In
large repositories, this can take a lot of time, so you may wish to
disable it in these repositories with git config --local
bash.showInformativeStatus false. It also changes the characters the
prompt uses to less plain ones (> instead of * for the dirty state
for example) , and if you are only interested in that, set
$__fish_git_prompt_use_informative_chars instead.
Because counting untracked files requires a lot of time, the number
of untracked files is only shown if enabled via
$__fish_git_prompt_showuntrackedfiles or the git option
bash.showUntrackedFiles.
o $__fish_git_prompt_showdirtystate or the git option
bash.showDirtyState can be set to 1, true or yes to show if the
repository is "dirty", i.e. has uncommitted changes.
o $__fish_git_prompt_showuntrackedfiles or the git option
bash.showUntrackedFiles can be set to 1, true or yes to show if the
repository has untracked files (that aren't ignored).
o $__fish_git_prompt_showupstream can be set to a list of values to
determine how changes between HEAD and upstream are shown:
auto summarize the difference between HEAD and its upstream
verbose
show number of commits ahead/behind (+/-) upstream
name if verbose, then also show the upstream abbrev name
informative
similar to verbose, but shows nothing when equal - this is
the default if informative status is enabled.
git always compare HEAD to @{upstream}
svn always compare HEAD to your SVN upstream
none disables (useful with informative status)
o $__fish_git_prompt_showstashstate can be set to 1, true or yes to
display the state of the stash.
o $__fish_git_prompt_shorten_branch_len can be set to the number of
characters that the branch name will be shortened to.
o $__fish_git_prompt_describe_style can be set to one of the following
styles to describe the current HEAD:
contains
relative to newer annotated tag, such as (v1.6.3.2~35)
branch relative to newer tag or branch, such as (master~4)
describe
relative to older annotated tag, such as
(v1.6.3.1-13-gdd42c2f)
default
an exactly matching tag ((develop))
If none of these apply, the commit SHA shortened to 8 characters
is used.
o $__fish_git_prompt_showcolorhints can be set to 1, true or yes to
enable coloring for the branch name and status symbols.
A number of variables set characters and color used as indicators. Many
of these have a different default if used with informative status
enabled, or $__fish_git_prompt_use_informative_chars set. The usual
default is given first, then the informative default (if it is
different). If no default for the colors is given, they default to
$__fish_git_prompt_color.
o $__fish_git_prompt_char_stateseparator (' ', |) - the character to be
used between the state characters
o $__fish_git_prompt_color (no default)
o $__fish_git_prompt_color_prefix - the color of the ( prefix
o $__fish_git_prompt_color_suffix - the color of the ) suffix
o $__fish_git_prompt_color_bare - the color to use for a bare
repository - one without a working tree
o $__fish_git_prompt_color_merging - the color when a
merge/rebase/revert/bisect or cherry-pick is in progress
o $__fish_git_prompt_char_cleanstate (> in informative mode) - the
character to be used when nothing else applies
o $__fish_git_prompt_color_cleanstate (no default)
Variables used with showdirtystate:
o $__fish_git_prompt_char_dirtystate (*, >) - the number of "dirty"
changes, i.e. unstaged files with changes
o $__fish_git_prompt_char_invalidstate (#, >) - the number of
"unmerged" changes, e.g. additional changes to already added files
o $__fish_git_prompt_char_stagedstate (+, >) - the number of staged
files without additional changes
o $__fish_git_prompt_color_dirtystate (red with showcolorhints, same as
color_flags otherwise)
o $__fish_git_prompt_color_invalidstate
o $__fish_git_prompt_color_stagedstate (green with showcolorhints,
color_flags otherwise)
Variables used with showstashstate:
o $__fish_git_prompt_char_stashstate ($, >)
o $__fish_git_prompt_color_stashstate (same as color_flags)
Variables used with showuntrackedfiles:
o $__fish_git_prompt_char_untrackedfiles (%, >) - the symbol for
untracked files
o $__fish_git_prompt_color_untrackedfiles (same as color_flags)
Variables used with showupstream (also implied by informative status):
o $__fish_git_prompt_char_upstream_ahead (>, ^) - the character for the
commits this repository is ahead of upstream
o $__fish_git_prompt_char_upstream_behind (<, v) - the character for
the commits this repository is behind upstream
o $__fish_git_prompt_char_upstream_diverged (<>) - the symbol if this
repository is both ahead and behind upstream
o $__fish_git_prompt_char_upstream_equal (=) - the symbol if this repo
is equal to upstream
o $__fish_git_prompt_char_upstream_prefix ('')
o $__fish_git_prompt_color_upstream
Colors used with showcolorhints:
o $__fish_git_prompt_color_branch (green) - the color of the branch if
nothing else applies
o $__fish_git_prompt_color_branch_detached (red) the color of the
branch if it's detached (e.g. a commit is checked out)
o $__fish_git_prompt_color_branch_dirty (no default) the color of the
branch if it's dirty and not detached
o $__fish_git_prompt_color_branch_staged (no default) the color of the
branch if it just has something staged and is otherwise clean
o $__fish_git_prompt_color_flags (--bold blue) - the default color for
dirty/staged/stashed/untracked state
Note that all colors can also have a corresponding _done color. For
example, the contents of $__fish_git_prompt_color_upstream_done is
printed right _after_ the upstream.
See also fish_vcs_prompt, which will call all supported version control
prompt functions, including git, Mercurial and Subversion.
Example
A simple prompt that displays git info:
function fish_prompt
# ...
set -g __fish_git_prompt_showupstream auto
printf '%s %s$' $PWD (fish_git_prompt)
end
fish_greeting - display a welcome message in interactive shells
Synopsis
fish_greeting
function fish_greeting
...
end
Description
When an interactive fish starts, it executes fish_greeting and displays
its output.
The default fish_greeting is a function that prints a variable of the
same name ($fish_greeting), so you can also just change that if you
just want to change the text.
While you could also just put echo calls into config.fish,
fish_greeting takes care of only being used in interactive shells, so
it won't be used e.g. with scp (which executes a shell), which prevents
some errors.
Example
To just empty the text, with the default greeting function:
set -U fish_greeting
or set -g fish_greeting in config.fish.
A simple greeting:
function fish_greeting
echo Hello friend!
echo The time is (set_color yellow)(date +%T)(set_color normal) and this machine is called $hostname
end
fish_hg_prompt - output Mercurial information for use in a prompt
Synopsis
fish_hg_prompt
function fish_prompt
printf '%s' $PWD (fish_hg_prompt) ' $ '
end
Description
The fish_hg_prompt function displays information about the current
Mercurial repository, if any.
Mercurial (hg) must be installed.
By default, only the current branch is shown because hg status can be
slow on a large repository. You can enable a more informative prompt by
setting the variable $fish_prompt_hg_show_informative_status, for
example:
set --universal fish_prompt_hg_show_informative_status
If you enabled the informative status, there are numerous customization
options, which can be controlled with fish variables.
o $fish_color_hg_clean, $fish_color_hg_modified and
$fish_color_hg_dirty are colors used when the repository has the
respective status.
Some colors for status symbols:
o $fish_color_hg_added
o $fish_color_hg_renamed
o $fish_color_hg_copied
o $fish_color_hg_deleted
o $fish_color_hg_untracked
o $fish_color_hg_unmerged
The status symbols themselves:
o $fish_prompt_hg_status_added, default '>'
o $fish_prompt_hg_status_modified, default '*'
o $fish_prompt_hg_status_copied, default '=>'
o $fish_prompt_hg_status_deleted, default '>'
o $fish_prompt_hg_status_untracked, default '?'
o $fish_prompt_hg_status_unmerged, default '!'
Finally, $fish_prompt_hg_status_order, which can be used to change the
order the status symbols appear in. It defaults to added modified
copied deleted untracked unmerged.
See also fish_vcs_prompt, which will call all supported version control
prompt functions, including git, Mercurial and Subversion.
Example
A simple prompt that displays hg info:
function fish_prompt
...
set -g fish_prompt_hg_show_informative_status
printf '%s %s$' $PWD (fish_hg_prompt)
end
fish_indent - indenter and prettifier
Synopsis
fish_indent [OPTIONS] [FILE ...]
Description
fish_indent is used to indent a piece of fish code. fish_indent reads
commands from standard input or the given filenames and outputs them to
standard output or a specified file (if -w is given).
The following options are available:
-w or --write
Indents a specified file and immediately writes to that file.
-i or --no-indent
Do not indent commands; only reformat to one job per line.
--only-indent
Do not reformat, only indent each line.
--only-unindent
Do not reformat, only unindent each line.
-c or --check
Do not indent, only return 0 if the code is already indented as
fish_indent would, the number of failed files otherwise. Also
print the failed filenames if not reading from standard input.
-v or --version
Displays the current fish version and then exits.
--ansi Colorizes the output using ANSI escape sequences, appropriate
for the current TERM, using the colors defined in the
environment (such as fish_color_command).
--html Outputs HTML, which supports syntax highlighting if the
appropriate CSS is defined. The CSS class names are the same as
the variable names, such as fish_color_command.
-d or --debug=DEBUG_CATEGORIES
Enable debug output and specify a pattern for matching debug
categories. See Debugging in fish (1) for details.
-o or --debug-output=DEBUG_FILE
Specify a file path to receive the debug output, including
categories and fish_trace. The default is standard error.
--dump-parse-tree
Dumps information about the parsed statements to standard error.
This is likely to be of interest only to people working on the
fish source code.
-h or --help
Displays help about using this command.
fish_is_root_user - check if the current user is root
Synopsis
fish_is_root_user
Description
fish_is_root_user will check if the current user is root. It can be
useful for the prompt to display something different if the user is
root, for example.
Example
A simple example:
function example --description 'Just an example'
if fish_is_root_user
do_something_different
end
end
fish_key_reader - explore what characters keyboard keys send
Synopsis
fish_key_reader [OPTIONS]
Description
fish_key_reader is used to explain how you would bind a certain key
sequence. By default, it prints the bind command for one key sequence
read interactively over standard input.
The following options are available:
-c or --continuous
Begins a session where multiple key sequences can be inspected.
By default the program exits after capturing a single key
sequence.
-h or --help
Displays help about using this command.
-V or --verbose
Explain what sequence was received in addition to the decoded
key.
-v or --version
Displays the current fish version and then exits.
Usage Notes
fish_key_reader intentionally disables handling of many signals. To
terminate fish_key_reader in --continuous mode do:
o press ctrl-c twice, or
o press ctrl-d twice, or
o type exit, or
o type quit
Example
> fish_key_reader
Press a key:
# press up-arrow
bind up 'do something'
fish_mode_prompt - define the appearance of the mode indicator
Synopsis
fish_mode_prompt
function fish_mode_prompt
echo -n "$fish_bind_mode "
end
Description
The fish_mode_prompt function outputs the mode indicator for use in vi
mode.
The default fish_mode_prompt function will output indicators about the
current vi editor mode displayed to the left of the regular prompt.
Define your own function to customize the appearance of the mode
indicator. The $fish_bind_mode variable can be used to determine the
current mode. It will be one of default, insert, replace_one, or
visual.
You can also define an empty fish_mode_prompt function to remove the vi
mode indicators:
function fish_mode_prompt; end
funcsave fish_mode_prompt
fish_mode_prompt will be executed when the vi mode changes. If it
produces any output, it is displayed and used. If it does not, the
other prompt functions (fish_prompt and fish_right_prompt) will be
executed as well in case they contain a mode display.
Example
function fish_mode_prompt
switch $fish_bind_mode
case default
set_color --bold red
echo 'N'
case insert
set_color --bold green
echo 'I'
case replace_one
set_color --bold green
echo 'R'
case visual
set_color --bold brmagenta
echo 'V'
case '*'
set_color --bold red
echo '?'
end
set_color normal
end
Outputting multiple lines is not supported in fish_mode_prompt.
fish_opt - create an option specification for the argparse command
Synopsis
fish_opt [(-slor | --multiple-vals=) OPTNAME]
fish_opt --help
Description
This command provides a way to produce option specifications suitable
for use with the argparse command. You can, of course, write the option
specifications by hand without using this command. But you might prefer
to use this for the clarity it provides.
The following argparse options are available:
-s or --short
Takes a single letter that is used as the short flag in the
option being defined. This option is mandatory.
-l or --long
Takes a string that is used as the long flag in the option being
defined. This option is optional and has no default. If no long
flag is defined then only the short flag will be allowed when
parsing arguments using the option specification.
--long-only
The option being defined will only allow the long flag name to
be used. The short flag name must still be defined (i.e.,
--short must be specified) but it cannot be used when parsing
arguments using this option specification.
-o or --optional-val
The option being defined can take a value, but it is optional
rather than required. If the option is seen more than once when
parsing arguments, only the last value seen is saved. This means
the resulting flag variable created by argparse will zero
elements if no value was given with the option else it will have
exactly one element.
-r or --required-val
The option being defined requires a value. If the option is seen
more than once when parsing arguments, only the last value seen
is saved. This means the resulting flag variable created by
argparse will have exactly one element.
--multiple-vals
The option being defined requires a value each time it is seen.
Each instance is stored. This means the resulting flag variable
created by argparse will have one element for each instance of
this option in the arguments.
-h or --help
Displays help about using this command.
Examples
Define a single option specification for the boolean help flag:
set -l options (fish_opt -s h -l help)
argparse $options -- $argv
Same as above but with a second flag that requires a value:
set -l options (fish_opt -s h -l help)
set options $options (fish_opt -s m -l max --required-val)
argparse $options -- $argv
Same as above but with a third flag that can be given multiple times
saving the value of each instance seen and only the long flag name
(--token) can be used:
set -l options (fish_opt --short=h --long=help)
set options $options (fish_opt --short=m --long=max --required-val)
set options $options (fish_opt --short=t --long=token --multiple-vals --long-only)
argparse $options -- $argv
fish_prompt - define the appearance of the command line prompt
Synopsis
fish_prompt
function fish_prompt
...
end
Description
The fish_prompt function is executed when the prompt is to be shown,
and the output is used as a prompt.
The exit status of commands within fish_prompt will not modify the
value of $status outside of the fish_prompt function.
fish ships with a number of example prompts that can be chosen with the
fish_config command.
Example
A simple prompt:
function fish_prompt -d "Write out the prompt"
# This shows up as USER@HOST /home/user/ >, with the directory colored
# $USER and $hostname are set by fish, so you can just use them
# instead of using `whoami` and `hostname`
printf '%s@%s %s%s%s > ' $USER $hostname \
(set_color $fish_color_cwd) (prompt_pwd) (set_color normal)
end
fish_right_prompt - define the appearance of the right-side command line
prompt
Synopsis
function fish_right_prompt
...
end
Description
fish_right_prompt is similar to fish_prompt, except that it appears on
the right side of the terminal window.
Multiple lines are not supported in fish_right_prompt.
Example
A simple right prompt:
function fish_right_prompt -d "Write out the right prompt"
date '+%m/%d/%y'
end
fish_should_add_to_history - decide whether a command should be added to
the history
Synopsis
fish_should_add_to_history
function fish_should_add_to_history
...
end
Description
The fish_should_add_to_history function is executed before fish adds a
command to history, and its return status decides whether that is done.
If it returns 0, the command is stored in history, when it returns
anything else, it is not. In the latter case the command can still be
recalled for one command.
The first argument to fish_should_add_to_history is the commandline.
History is added before a command is run, so e.g. status can't be
checked. This is so commands that don't finish like exec - execute
command in current process and long-running commands are available in
new sessions immediately.
If fish_should_add_to_history doesn't exist, fish will save a command
to history unless it starts with a space. If it does exist, this
function takes over all of the duties, so commands starting with space
are saved unless fish_should_add_to_history says otherwise.
Example
A simple example:
function fish_should_add_to_history
for cmd in vault mysql ls
string match -qr "^$cmd" -- $argv; and return 1
end
return 0
end
This refuses to store any immediate "vault", "mysql" or "ls" calls.
Commands starting with space would be stored.
function fish_should_add_to_history
# I don't want `git pull`s in my history when I'm in a specific repository
if string match -qr '^git pull'
and string match -qr "^/home/me/my-secret-project/" -- (pwd -P)
return 1
end
return 0
end
fish_status_to_signal - convert exit codes to human-friendly signals
Synopsis
fish_status_to_signal NUM
function fish_prompt
echo -n (fish_status_to_signal $pipestatus | string join '|') (prompt_pwd) '$ '
end
Description
fish_status_to_signal converts exit codes to their corresponding
human-friendly signals if one exists. This is likely to be useful for
prompts in conjunction with the $status and $pipestatus variables.
Example
>_ sleep 5
^C>
>_ fish_status_to_signal $status
SIGINT
fish_svn_prompt - output Subversion information for use in a prompt
Synopsis
fish_svn_prompt
function fish_prompt
printf '%s' $PWD (fish_svn_prompt) ' $ '
end
Description
The fish_svn_prompt function displays information about the current
Subversion repository, if any.
Subversion (svn) must be installed.
There are numerous customization options, which can be controlled with
fish variables.
o
__fish_svn_prompt_color_revision
the colour of the revision number to display in the prompt
o
__fish_svn_prompt_char_separator
the separator between status characters
A number of variables control the symbol ("display") and color
("color") for the different status indicators:
o __fish_svn_prompt_char_added_display
o __fish_svn_prompt_char_added_color
o __fish_svn_prompt_char_conflicted_display
o __fish_svn_prompt_char_conflicted_color
o __fish_svn_prompt_char_deleted_display
o __fish_svn_prompt_char_deleted_color
o __fish_svn_prompt_char_ignored_display
o __fish_svn_prompt_char_ignored_color
o __fish_svn_prompt_char_modified_display
o __fish_svn_prompt_char_modified_color
o __fish_svn_prompt_char_replaced_display
o __fish_svn_prompt_char_replaced_color
o __fish_svn_prompt_char_unversioned_external_display
o __fish_svn_prompt_char_unversioned_external_color
o __fish_svn_prompt_char_unversioned_display
o __fish_svn_prompt_char_unversioned_color
o __fish_svn_prompt_char_missing_display
o __fish_svn_prompt_char_missing_color
o __fish_svn_prompt_char_versioned_obstructed_display
o __fish_svn_prompt_char_versioned_obstructed_color
o __fish_svn_prompt_char_locked_display
o __fish_svn_prompt_char_locked_color
o __fish_svn_prompt_char_scheduled_display
o __fish_svn_prompt_char_scheduled_color
o __fish_svn_prompt_char_switched_display
o __fish_svn_prompt_char_switched_color
o __fish_svn_prompt_char_token_present_display
o __fish_svn_prompt_char_token_present_color
o __fish_svn_prompt_char_token_other_display
o __fish_svn_prompt_char_token_other_color
o __fish_svn_prompt_char_token_stolen_display
o __fish_svn_prompt_char_token_stolen_color
o __fish_svn_prompt_char_token_broken_display
o __fish_svn_prompt_char_token_broken_color
See also fish_vcs_prompt, which will call all supported version control
prompt functions, including git, Mercurial and Subversion.
Example
A simple prompt that displays svn info:
function fish_prompt
...
printf '%s %s$' $PWD (fish_svn_prompt)
end
fish_title - define the terminal's title
Synopsis
fish_title
function fish_title
...
end
Description
The fish_title function is executed before and after a new command is
executed or put into the foreground and the output is used as a
titlebar message.
The first argument to fish_title contains the most recently executed
foreground command as a string, if any.
This requires that your terminal supports programmable titles and the
feature is turned on.
Example
A simple title:
function fish_title
set -q argv[1]; or set argv fish
# Looks like ~/d/fish: git log
# or /e/apt: fish
echo (fish_prompt_pwd_dir_length=1 prompt_pwd): $argv;
end
fish_update_completions - update completions using manual pages
Synopsis
fish_update_completions
Description
fish_update_completions parses manual pages installed on the system,
and attempts to create completion files in the fish configuration
directory.
This does not overwrite custom completions.
There are no parameters for fish_update_completions.
fish_vcs_prompt - output version control system information for use in a
prompt
Synopsis
fish_vcs_prompt
function fish_prompt
printf '%s' $PWD (fish_vcs_prompt) ' $ '
end
Description
The fish_vcs_prompt function displays information about the current
version control system (VCS) repository, if any.
It calls out to VCS-specific functions. The currently supported systems
are:
o fish_git_prompt
o fish_hg_prompt
o fish_svn_prompt
If a VCS isn't installed, the respective function does nothing.
The Subversion prompt is disabled by default, because it's slow on
large repositories. To enable it, modify fish_vcs_prompt to uncomment
it. See funced.
For more information, see the documentation for each of the functions
above.
Example
A simple prompt that displays all known VCS info:
function fish_prompt
...
set -g __fish_git_prompt_showupstream auto
printf '%s %s$' $PWD (fish_vcs_prompt)
end
fish_vi_key_bindings - set vi key bindings for fish
Synopsis
fish_vi_key_bindings
fish_vi_key_bindings [--no-erase] [INIT_MODE]
Description
fish_vi_key_bindings sets the vi key bindings for fish shell.
If a valid INIT_MODE is provided (insert, default, visual), then that
mode will become the default . If no INIT_MODE is given, the mode
defaults to insert mode.
The following parameters are available:
--no-erase
Does not clear previous set bindings
Further information on how to use vi mode.
Examples
To start using vi key bindings:
fish_vi_key_bindings
or set -g fish_key_bindings fish_vi_key_bindings in config.fish.
for - perform a set of commands multiple times
Synopsis
for VARNAME in [VALUES ...]; COMMANDS ...; end
Description
for is a loop construct. It will perform the commands specified by
COMMANDS multiple times. On each iteration, the local variable
specified by VARNAME is assigned a new value from VALUES. If VALUES is
empty, COMMANDS will not be executed at all. The VARNAME is visible
when the loop terminates and will contain the last value assigned to
it. If VARNAME does not already exist it will be set in the local
scope. For our purposes if the for block is inside a function there
must be a local variable with the same name. If the for block is not
nested inside a function then global and universal variables of the
same name will be used if they exist.
Much like set, for does not modify $status, but the evaluation of its
subordinate commands can.
The -h or --help option displays help about using this command.
Example
for i in foo bar baz; echo $i; end
# would output:
foo
bar
baz
Notes
The VARNAME was local to the for block in releases prior to 3.0.0. This
means that if you did something like this:
for var in a b c
if break_from_loop
break
end
end
echo $var
The last value assigned to var when the loop terminated would not be
available outside the loop. What echo $var would write depended on what
it was set to before the loop was run. Likely nothing.
funced - edit a function interactively
Synopsis
funced [OPTIONS] NAME
Description
funced provides an interface to edit the definition of the function
NAME.
If the $VISUAL environment variable is set, it will be used as the
program to edit the function. If $VISUAL is unset but $EDITOR is set,
that will be used. Otherwise, a built-in editor will be used. Note that
to enter a literal newline using the built-in editor you should press
alt-enter. Pressing enter signals that you are done editing the
function. This does not apply to an external editor like emacs or vim.
funced will try to edit the original file that a function is defined
in, which might include variable definitions or helper functions as
well. If changes cannot be saved to the original file, a copy will be
created in the user's function directory.
If there is no function called NAME, a new function will be created
with the specified name.
-e command or --editor command
Open the function body inside the text editor given by the
command (for example, -e vi). The special command fish will use
the built-in editor (same as specifying -i).
-i or --interactive
Force opening the function body in the built-in editor even if
$VISUAL or $EDITOR is defined.
-s or --save
Automatically save the function after successfully editing it.
-h or --help
Displays help about using this command.
Example
Say you want to modify your prompt.
Run:
>_ funced fish_prompt
This will open up your editor, allowing you to modify the function.
When you're done, save and quit. Fish will reload the function, so you
should see the changes right away.
When you're done, use:
>_ funcsave fish_prompt
For more, see funcsave. To view a function's current definition, use
functions or type.
funcsave - save the definition of a function to the user's autoload
directory
Synopsis
funcsave FUNCTION_NAME
funcsave [-q | --quiet] [(-d | --directory) DIR] FUNCTION_NAME
Description
funcsave saves a function to a file in the fish configuration
directory. This function will be automatically loaded by current and
future fish sessions. This can be useful to commit functions created
interactively for permanent use.
If you have erased a function using functions's --erase option,
funcsave will remove the saved function definition.
Because fish loads functions on-demand, saved functions cannot serve as
event handlers until they are run or otherwise sourced. To activate an
event handler for every new shell, add the function to the
configuration file instead of using funcsave.
This is often used after funced, which opens the function in $EDITOR or
$VISUAL and loads it into the current session afterwards.
To view a function's current definition, use functions or type.
function - create a function
Synopsis
function NAME [OPTIONS]; BODY; end
Description
function creates a new function NAME with the body BODY.
A function is a list of commands that will be executed when the name of
the function is given as a command.
The following options are available:
-a NAMES or --argument-names NAMES
Has to be the last option. Assigns the value of successive
command-line arguments to the names given in NAMES (separated by
space). These are the same arguments given in argv, and are
still available there. See also Argument Handling.
-d DESCRIPTION or --description DESCRIPTION
A description of what the function does, suitable as a
completion description.
-w WRAPPED_COMMAND or --wraps WRAPPED_COMMAND
Inherit completions from the given WRAPPED_COMMAND. See the
documentation for complete for more information.
-e EVENT_NAME or --on-event EVENT_NAME
Run this function when the specified named event is emitted.
Fish internally generates named events, for example, when
showing the prompt. Custom events can be emitted using the emit
command.
-v VARIABLE_NAME or --on-variable VARIABLE_NAME
Run this function when the variable VARIABLE_NAME changes value.
Note that fish makes no guarantees on any particular timing or
even that the function will be run for every single set. Rather
it will be run when the variable has been set at least once,
possibly skipping some values or being run when the variable has
been set to the same value (except for universal variables set
in other shells - only changes in the value will be picked up
for those).
-j PID or --on-job-exit PID
Run this function when the job containing a child process with
the given process identifier PID exits. Instead of a PID, the
string 'caller' can be specified. This is only allowed when in a
command substitution, and will result in the handler being
triggered by the exit of the job which created this command
substitution. This will not trigger for disowned jobs.
-p PID or --on-process-exit PID
Run this function when the fish child process with process ID
PID exits. Instead of a PID, for backward compatibility, "%self"
can be specified as an alias for $fish_pid, and the function
will be run when the current fish instance exits. This will not
trigger for disowned jobs.
-s SIGSPEC or --on-signal SIGSPEC
Run this function when the signal SIGSPEC is delivered. SIGSPEC
can be a signal number, or the signal name, such as SIGHUP (or
just HUP). Note that the signal must have been delivered to
fish; for example, ctrl-c sends SIGINT to the foreground process
group, which will not be fish if you are running another command
at the time. Observing a signal will prevent fish from exiting
in response to that signal.
-S or --no-scope-shadowing
Allows the function to access the variables of calling
functions. Normally, any variables inside the function that have
the same name as variables from the calling function are
"shadowed", and their contents are independent of the calling
function.
It's important to note that this does not capture referenced
variables or the scope at the time of function declaration! At
this time, fish does not have any concept of closures, and
variable lifetimes are never extended. In other words, by using
--no-scope-shadowing the scope of the function each time it is
run is shared with the scope it was called from rather than the
scope it was defined in.
-V or --inherit-variable NAME
Snapshots the value of the variable NAME and defines a local
variable with that same name and value when the function is
defined. This is similar to a closure in other languages like
Python but a bit different. Note the word "snapshot" in the
first sentence. If you change the value of the variable after
defining the function, even if you do so in the same scope
(typically another function) the new value will not be used by
the function you just created using this option. See the
function notify example below for how this might be used.
The event handler switches (on-event, on-variable, on-job-exit,
on-process-exit and on-signal) cause a function to run automatically at
specific events. New named events for --on-event can be fired using the
emit builtin. Fish already generates a few events, see Event handlers
for more.
Functions names cannot be reserved words. These are elements of fish
syntax or builtin commands which are essential for the operations of
the shell. Current reserved words are [, _, and, argparse, begin,
break, builtin, case, command, continue, else, end, eval, exec, for,
function, if, not, or, read, return, set, status, string, switch, test,
time, and while.
Example
function ll
ls -l $argv
end
will run the ls command, using the -l option, while passing on any
additional files and switches to ls.
function debug -a name val
echo [DEBUG] $name: $val >&2
end
set foo bar
debug foo bar
# prints: [DEBUG] foo: bar
# OR
function debug2 -a var
echo [DEBUG] $var: $$var >&2
end
set foo bar
debug2 foo
# prints: [DEBUG] foo: bar
will create a debug command to print chosen variables to stderr.
function mkdir -d "Create a directory and set CWD"
command mkdir $argv
if test $status = 0
switch $argv[(count $argv)]
case '-*'
case '*'
cd $argv[(count $argv)]
return
end
end
end
This will run the mkdir command, and if it is successful, change the
current working directory to the one just created.
function notify
set -l job (jobs -l -g)
or begin; echo "There are no jobs" >&2; return 1; end
function _notify_job_$job --on-job-exit $job --inherit-variable job
echo -n \a # beep
functions -e _notify_job_$job
end
end
This will beep when the most recent job completes.
Notes
Events are only received from the current fish process as there is no
way to send events from one fish process to another.
See more
For more explanation of how functions fit into fish, see Functions.
functions - print or erase functions
Synopsis
functions [-a | --all] [-n | --names]
functions [-D | --details] [-v] FUNCTION
functions -c OLDNAME NEWNAME
functions -d DESCRIPTION FUNCTION
functions [-e | -q] FUNCTION ...
Description
functions prints or erases functions.
The following options are available:
-a or --all
Lists all functions, even those whose name starts with an
underscore.
-c or --copy OLDNAME NEWNAME
Creates a new function named NEWNAME, using the definition of
the OLDNAME function.
-d or --description DESCRIPTION
Changes the description of this function.
-e or --erase
Causes the specified functions to be erased. This also means
that it is prevented from autoloading in the current session.
Use funcsave to remove the saved copy.
-D or --details
Reports the path name where the specified function is defined or
could be autoloaded, stdin if the function was defined
interactively or on the command line or by reading standard
input, - if the function was created via source, and n/a if the
function isn't available. (Functions created via alias will
return -, because alias uses source internally. Copied functions
will return where the function was copied.) If the --verbose
option is also specified then five lines are written:
o the path name as already described,
o if the function was copied, the path name to where the
function was originally defined, otherwise autoloaded,
not-autoloaded or n/a,
o the line number within the file or zero if not applicable,
o scope-shadowing if the function shadows the vars in the
calling function (the normal case if it wasn't defined with
--no-scope-shadowing), else no-scope-shadowing, or n/a if the
function isn't defined,
o the function description minimally escaped so it is a single
line, or n/a if the function isn't defined or has no
description.
You should not assume that only five lines will be written since
we may add additional information to the output in the future.
--no-details
Turns off function path reporting, so just the definition will
be printed.
-n or --names
Lists the names of all defined functions.
-q or --query
Tests if the specified functions exist.
-v or --verbose
Make some output more verbose.
-H or --handlers
Show all event handlers.
-t or --handlers-type TYPE
Show all event handlers matching the given TYPE.
-h or --help
Displays help about using this command.
The default behavior of functions, when called with no arguments, is to
print the names of all defined functions. Unless the -a option is
given, no functions starting with underscores are included in the
output.
If any non-option parameters are given, the definition of the specified
functions are printed.
Copying a function using -c copies only the body of the function, and
does not attach any event notifications from the original function.
Only one function's description can be changed in a single invocation
of functions -d.
The exit status of functions is the number of functions specified in
the argument list that do not exist, which can be used in concert with
the -q option.
Examples
functions -n
# Displays a list of currently-defined functions
functions -c foo bar
# Copies the 'foo' function to a new function called 'bar'
functions -e bar
# Erases the function ``bar``
See more
For more explanation of how functions fit into fish, see Functions.
help - display fish documentation
Synopsis
help [SECTION]
Description
help displays the fish help documentation.
If a SECTION is specified, the help for that command is shown.
The -h or --help option displays help about using this command.
If the BROWSER environment variable is set, it will be used to display
the documentation. Otherwise, fish will search for a suitable browser.
To use a different browser than as described above, you can set
$fish_help_browser This variable may be set as a list, where the first
element is the browser command and the rest are browser options.
Example
help fg shows the documentation for the fg builtin.
Notes
Most builtin commands, including this one, display their help in the
terminal when given the --help option.
history - show and manipulate command history
Synopsis
history [search] [--show-time] [--case-sensitive]
[--exact | --prefix | --contains] [--max N] [--null] [--reverse]
[SEARCH_STRING ...]
history delete [--case-sensitive]
[--exact | --prefix | --contains] SEARCH_STRING ...
history merge
history save
history clear
history clear-session
history append COMMAND ...
Description
history is used to search, delete, and otherwise manipulate the history
of interactive commands.
The following operations (sub-commands) are available:
search Returns history items matching the search string. If no search
string is provided it returns all history items. This is the
default operation if no other operation is specified. You only
have to explicitly say history search if you wish to search for
one of the subcommands. The --contains search option will be
used if you don't specify a different search option. Entries are
ordered newest to oldest unless you use the --reverse flag. If
stdout is attached to a tty the output will be piped through
your pager by the history function. The history builtin simply
writes the results to stdout.
delete Deletes history items. The --contains search option will be used
if you don't specify a different search option. If you don't
specify --exact a prompt will be displayed before any items are
deleted asking you which entries are to be deleted. You can
enter the word "all" to delete all matching entries. You can
enter a single ID (the number in square brackets) to delete just
that single entry. You can enter more than one ID, or an ID
range separated by a space to delete multiple entries. Just
press [enter] to not delete anything. Note that the interactive
delete behavior is a feature of the history function. The
history builtin only supports --exact --case-sensitive deletion.
merge Immediately incorporates history changes from other sessions.
Ordinarily fish ignores history changes from sessions started
after the current one. This command applies those changes
immediately.
save Immediately writes all changes to the history file. The shell
automatically saves the history file; this option is provided
for internal use and should not normally need to be used by the
user.
clear Clears the history file. A prompt is displayed before the
history is erased asking you to confirm you really want to clear
all history unless builtin history is used.
clear-session
Clears the history file from all activity of the current
session. Note: If history merge or builtin history merge is run
in a session, only the history after this will be erased.
append Appends commands to the history without needing to execute them.
The following options are available:
These flags can appear before or immediately after one of the
sub-commands listed above.
-C or --case-sensitive
Does a case-sensitive search. The default is case-insensitive.
Note that prior to fish 2.4.0 the default was case-sensitive.
-c or --contains
Searches items in the history that contain the specified text
string. This is the default for the --search flag. This is not
currently supported by the delete subcommand.
-e or --exact
Searches or deletes items in the history that exactly match the
specified text string. This is the default for the delete
subcommand. Note that the match is case-insensitive by default.
If you really want an exact match, including letter case, you
must use the -C or --case-sensitive flag.
-p or --prefix
Searches items in the history that begin with the specified text
string. This is not currently supported by the delete
subcommand.
-t or --show-time
Prepends each history entry with the date and time the entry was
recorded. By default it uses the strftime format # %c%n. You can
specify another format; e.g., --show-time="%Y-%m-%d %H:%M:%S "
or --show-time="%a%I%p". The short option, -t, doesn't accept a
strftime format string; it only uses the default format. Any
strftime format is allowed, including %s to get the raw UNIX
seconds since the epoch.
-z or --null
Causes history entries written by the search operations to be
terminated by a NUL character rather than a newline. This allows
the output to be processed by read -z to correctly handle
multiline history entries.
-*NUMBER* -n NUMBER or --max NUMBER
Limits the matched history items to the first NUMBER matching
entries. This is only valid for history search.
-R or --reverse
Causes the history search results to be ordered oldest to
newest. Which is the order used by most shells. The default is
newest to oldest.
-h or --help
Displays help for this command.
Example
history clear
# Deletes all history items
history search --contains "foo"
# Outputs a list of all previous commands containing the string "foo".
history delete --prefix "foo"
# Interactively deletes commands which start with "foo" from the history.
# You can select more than one entry by entering their IDs separated by a space.
Customizing the name of the history file
By default interactive commands are logged to
$XDG_DATA_HOME/fish/fish_history (typically
~/.local/share/fish/fish_history).
You can set the fish_history variable to another name for the current
shell session. The default value (when the variable is unset) is fish
which corresponds to $XDG_DATA_HOME/fish/fish_history. If you set it to
e.g. fun, the history would be written to
$XDG_DATA_HOME/fish/fun_history. An empty string means history will not
be stored at all. This is similar to the private session features in
web browsers.
You can change fish_history at any time (by using set -x fish_history
"session_name") and it will take effect right away. If you set it to
"default", it will use the default session name (which is "fish").
Other shells such as bash and zsh use a variable named HISTFILE for a
similar purpose. Fish uses a different name to avoid conflicts and
signal that the behavior is different (session name instead of a file
path). Also, if you set the var to anything other than fish or default
it will inhibit importing the bash history. That's because the most
common use case for this feature is to avoid leaking private or
sensitive history when giving a presentation.
Notes
If you specify both --prefix and --contains the last flag seen is used.
Note that for backwards compatibility each subcommand can also be
specified as a long option. For example, rather than history search you
can type history --search. Those long options are deprecated and will
be removed in a future release.
if - conditionally execute a command
Synopsis
if CONDITION; COMMANDS_TRUE ...;
[else if CONDITION2; COMMANDS_TRUE2 ...;]
[else; COMMANDS_FALSE ...;]
end
Description
if will execute the command CONDITION. If the condition's exit status
is 0, the commands COMMANDS_TRUE will execute. If the exit status is
not 0 and else is given, COMMANDS_FALSE will be executed.
You can use and or or in the condition. See the second example below.
The exit status of the last foreground command to exit can always be
accessed using the $status variable.
The -h or --help option displays help about using this command.
Example
The following code will print foo.txt exists if the file foo.txt exists
and is a regular file, otherwise it will print bar.txt exists if the
file bar.txt exists and is a regular file, otherwise it will print
foo.txt and bar.txt do not exist.
if test -f foo.txt
echo foo.txt exists
else if test -f bar.txt
echo bar.txt exists
else
echo foo.txt and bar.txt do not exist
end
The following code will print "foo.txt exists and is readable" if
foo.txt is a regular file and readable
if test -f foo.txt
and test -r foo.txt
echo "foo.txt exists and is readable"
end
See also
if is only as useful as the command used as the condition.
Fish ships a few:
o test - perform tests on files and text can compare numbers, strings
and check paths
o string - manipulate strings can perform string operations including
wildcard and regular expression matches
o path - manipulate and check paths can check paths for permissions,
existence or type
o contains - test if a word is present in a list can check if an
element is in a list
isatty - test if a file descriptor is a terminal
Synopsis
isatty [FILE_DESCRIPTOR]
Description
isatty tests if a file descriptor is a terminal (as opposed to a file).
The name is derived from the system call of the same name, which for
historical reasons refers to a teletypewriter (TTY).
FILE DESCRIPTOR may be either the number of a file descriptor, or one
of the strings stdin, stdout, or stderr. If not specified, zero is
assumed.
If the specified file descriptor is a terminal device, the exit status
of the command is zero. Otherwise, the exit status is non-zero. No
messages are printed to standard error.
The -h or --help option displays help about using this command.
Examples
From an interactive shell, the commands below exit with a return value
of zero:
isatty
isatty stdout
isatty 2
echo | isatty 1
And these will exit non-zero:
echo | isatty
isatty 9
isatty stdout > file
isatty 2 2> file
jobs - print currently running jobs
Synopsis
jobs [OPTIONS] [PID | %JOBID]
Description
NOTE: This page documents the fish builtin jobs. To see the
documentation on any non-fish versions, use command man jobs.
jobs prints a list of the currently running jobs and their status.
jobs accepts the following options:
-c or --command
Prints the command name for each process in jobs.
-g or --group
Only prints the group ID of each job.
-l or --last
Prints only the last job to be started.
-p or --pid
Prints the process ID for each process in all jobs.
-q or --query
Prints no output for evaluation of jobs by exit status only. For
compatibility with old fish versions this is also --quiet (but
this is deprecated).
-h or --help
Displays help about using this command.
On systems that support this feature, jobs will print the CPU usage of
each job since the last command was executed. The CPU usage is
expressed as a percentage of full CPU activity. Note that on
multiprocessor systems, the total activity may be more than 100%.
Arguments of the form PID or %JOBID restrict the output to jobs with
the selected process identifiers or job numbers respectively.
If the output of jobs is redirected or if it is part of a command
substitution, the column header that is usually printed is omitted,
making it easier to parse.
The exit status of jobs is 0 if there are running background jobs and 1
otherwise.
Example
jobs outputs a summary of the current jobs, such as two long-running
tasks in this example:
Job Group State Command
2 26012 running nc -l 55232 < /dev/random &
1 26011 running python tests/test_11.py &
math - perform mathematics calculations
Synopsis
math [(-s | --scale) N] [(-b | --base) BASE] [(-m | --scale-mode) MODE] EXPRESSION ...
Description
math performs mathematical calculations. It supports simple operations
such as addition, subtraction, and so on, as well as functions like
abs(), sqrt() and ln().
By default, the output shows up to 6 decimal places. To change the
number of decimal places, use the --scale option, including --scale=0
for integer output.
Keep in mind that parameter expansion happens before expressions are
evaluated. This can be very useful in order to perform calculations
involving shell variables or the output of command substitutions, but
it also means that parenthesis (()) and the asterisk (*) glob character
have to be escaped or quoted. x can also be used to denote
multiplication, but it needs to be followed by whitespace to
distinguish it from hexadecimal numbers.
Parentheses for functions are optional - math sin pi prints 0.
However, a comma will bind to the inner function, so math pow sin 3, 5
is an error because it tries to give sin the arguments 3 and 5. When
in doubt, use parentheses.
math ignores whitespace between arguments and takes its input as
multiple arguments (internally joined with a space), so math 2 +2 and
math "2 + 2" work the same. math 2 2 is an error.
The following options are available:
-s N or --scale N
Sets the scale of the result. N must be an integer or the word
"max" for the maximum scale. A scale of zero causes results to
be truncated by default. Any non-integer component is thrown
away. So 3/2 returns 1 by default, rather than 2 which 1.5
would normally round to. This is for compatibility with bc
which was the basis for this command prior to fish 3.0.0. Scale
values greater than zero causes the result to be rounded using
the usual rules to the specified number of decimal places.
-b BASE or --base BASE
Sets the numeric base used for output (math always understands
hexadecimal numbers as input). It currently understands "hex"
or "16" for hexadecimal and "octal" or "8" for octal and implies
a scale of 0 (other scales cause an error), so it will truncate
the result down to an integer. This might change in the future.
Hex numbers will be printed with a 0x prefix. Octal numbers
will have a prefix of 0 but aren't understood by math as input.
-m MODE or --scale-mode MODE
Sets scale behavior. The MODE can be truncate, round, floor,
ceiling. The default value of scale mode is round with non zero
scale and truncate with zero scale.
-h or --help
Displays help about using this command.
Return Values
If the expression is successfully evaluated and doesn't over/underflow
or return NaN the return status is zero (success) else one.
Syntax
math knows some operators, constants, functions and can (obviously)
read numbers.
For numbers, . is always the radix character regardless of locale -
2.5, not 2,5. Scientific notation (10e5) and hexadecimal (0xFF) are
also available.
math allows you to use underscores as visual separators for digit
grouping. For example, you can write 1_000_000, 0x_89_AB_CD_EF, and
1.234_567_e89.
Operators
math knows the following operators:
+ for addition
- for subtraction
* or x for multiplication. * is the glob character and needs to be
quoted or escaped, x needs to be followed by whitespace or it
looks like 0x hexadecimal notation.
/ for division
^ for exponentiation
% for modulo
( or ) for grouping. These need to be quoted or escaped because ()
denotes a command substitution.
They are all used in an infix manner - 5 + 2, not + 5 2.
Constants
math knows the following constants:
e Euler's number
pi , you know this one. Half of Tau
tau Equivalent to 2, or the number of radians in a circle
Use them without a leading $ - pi - 3 should be about 0.
Functions
math supports the following functions:
abs the absolute value, with positive sign
acos arc cosine
asin arc sine
atan arc tangent
atan2 arc tangent of two variables
bitand, bitor and bitxor
perform bitwise operations. These will throw away any
non-integer parts and interpret the rest as an int.
Note: bitnot and bitnand don't exist. This is because numbers in
math don't really have a width in terms of bits, and these
operations necessarily care about leading zeroes.
If you need to negate a specific number you can do it with an
xor with a mask, e.g.:
> math --base=hex bitxor 0x0F, 0xFF
0xF0
> math --base=hex bitxor 0x2, 0x3
# Here we mask with 0x3 == 0b111, so our number is 3 bits wide
# Only the 1 bit isn't set.
0x1
ceil round number up to the nearest integer
cos the cosine
cosh hyperbolic cosine
exp the base-e exponential function
fac factorial - also known as x! (x * (x - 1) * (x - 2) * ... * 1)
floor round number down to the nearest integer
ln the base-e logarithm
log or log10
the base-10 logarithm
log2 the base-2 logarithm
max returns the largest of the given numbers - this takes an
arbitrary number of arguments (but at least one)
min returns the smallest of the given numbers - this takes an
arbitrary number of arguments (but at least one)
ncr "from n choose r" combination function - how many subsets of
size r can be taken from n (order doesn't matter)
npr the number of subsets of size r that can be taken from a set of
n elements (including different order)
pow(x,y)
returns x to the y (and can be written as x ^ y)
round rounds to the nearest integer, away from 0
sin the sine function
sinh the hyperbolic sine
sqrt the square root - (can also be written as x ^ 0.5)
tan the tangent
tanh the hyperbolic tangent
All of the trigonometric functions use radians (the pi-based scale, not
360).
Examples
math 1+1 outputs 2.
math $status - 128 outputs the numerical exit status of the last
command minus 128.
math 10 / 6 outputs 1.666667.
math -s0 10.0 / 6.0 outputs 1.
math -s3 10 / 6 outputs 1.667.
math "sin(pi)" outputs 0.
math 5 \* 2 or math "5 * 2" or math 5 "*" 2 all output 10.
math 0xFF outputs 255, math 0 x 3 outputs 0 (because it computes 0
multiplied by 3).
math bitand 0xFE, 0x2e outputs 46.
math "bitor(9,2)" outputs 11.
math --base=hex 192 prints 0xc0.
math 'ncr(49,6)' prints 13983816 - that's the number of possible picks
in 6-from-49 lotto.
math max 5,2,3,1 prints 5.
Compatibility notes
Fish 1.x and 2.x releases relied on the bc command for handling math
expressions. Starting with fish 3.0.0 fish uses the tinyexpr library
and evaluates the expression without the involvement of any external
commands.
You don't need to use -- before the expression, even if it begins with
a minus sign which might otherwise be interpreted as an invalid option.
If you do insert -- before the expression, it will cause option
scanning to stop just like for every other command and it won't be part
of the expression.
nextd - move forward through directory history
Synopsis
nextd [-l | --list] [POS]
Description
nextd moves forwards POS positions in the history of visited
directories; if the end of the history has been hit, a warning is
printed.
If the -l or --list option is specified, the current directory history
is also displayed.
The -h or --help option displays help about using this command.
Note that the cd command limits directory history to the 25 most
recently visited directories. The history is stored in the dirprev and
dirnext variables which this command manipulates.
Example
cd /usr/src
# Working directory is now /usr/src
cd /usr/src/fish-shell
# Working directory is now /usr/src/fish-shell
prevd
# Working directory is now /usr/src
nextd
# Working directory is now /usr/src/fish-shell
See Also
o the cdh command to display a prompt to quickly navigate the history
o the dirh command to print the directory history
o the prevd command to move backward
not - negate the exit status of a job
Synopsis
not COMMAND [OPTIONS ...]
! COMMAND [OPTIONS ...]
Description
not negates the exit status of another command. If the exit status is
zero, not returns 1. Otherwise, not returns 0.
Some other shells only support the ! alias.
The -h or --help option displays help about using this command.
Example
The following code reports an error and exits if no file named spoon
can be found.
if not test -f spoon
echo There is no spoon
exit 1
end
open - open file in its default application
Synopsis
open FILES ...
Description
open opens a file in its default application, using the appropriate
tool for the operating system. On GNU/Linux, this requires the common
but optional xdg-open utility, from the xdg-utils package.
Note that this function will not be used if a command by this name
exists (which is the case on macOS or Haiku).
Example
open *.txt opens all the text files in the current directory using your
system's default text editor.
or - conditionally execute a command
Synopsis
COMMAND1; or COMMAND2
Description
or is used to execute a command if the previous command was not
successful (returned a status of something other than 0).
or statements may be used as part of the condition in an if or while
block.
or does not change the current exit status itself, but the command it
runs most likely will. The exit status of the last foreground command
to exit can always be accessed using the $status variable.
The -h or --help option displays help about using this command.
Example
The following code runs the make command to build a program. If the
build succeeds, the program is installed. If either step fails, make
clean is run, which removes the files created by the build process.
make; and make install; or make clean
See Also
o and command
path - manipulate and check paths
Synopsis
path basename GENERAL_OPTIONS [(-E | --no-extension)] [PATH ...]
path dirname GENERAL_OPTIONS [PATH ...]
path extension GENERAL_OPTIONS [PATH ...]
path filter GENERAL_OPTIONS [-v | --invert]
[-d] [-f] [-l] [-r] [-w] [-x]
[(-t | --type) TYPE] [(-p | --perm) PERMISSION] [PATH ...]
path is GENERAL_OPTIONS [(-v | --invert)] [(-t | --type) TYPE]
[-d] [-f] [-l] [-r] [-w] [-x]
[(-p | --perm) PERMISSION] [PATH ...]
path mtime GENERAL_OPTIONS [(-R | --relative)] [PATH ...]
path normalize GENERAL_OPTIONS [PATH ...]
path resolve GENERAL_OPTIONS [PATH ...]
path change-extension GENERAL_OPTIONS EXTENSION [PATH ...]
path sort GENERAL_OPTIONS [-r | --reverse]
[-u | --unique] [--key=basename|dirname|path] [PATH ...]
GENERAL_OPTIONS
[-z | --null-in] [-Z | --null-out] [-q | --quiet]
Description
path performs operations on paths.
PATH arguments are taken from the command line unless standard input is
connected to a pipe or a file, in which case they are read from
standard input, one PATH per line. It is an error to supply PATH
arguments on both the command line and on standard input.
Arguments starting with - are normally interpreted as switches; --
causes the following arguments not to be treated as switches even if
they begin with -. Switches and required arguments are recognized only
on the command line.
When a path starts with -, path filter and path normalize will prepend
./ on output to avoid it being interpreted as an option otherwise, so
it's safe to pass path's output to other commands that can handle
relative paths.
All subcommands accept a -q or --quiet switch, which suppresses the
usual output but exits with the documented status. In this case these
commands will quit early, without reading all of the available input.
All subcommands also accept a -Z or --null-out switch, which makes them
print output separated with NUL instead of newlines. This is for
further processing, e.g. passing to another path, or xargs -0. This is
not recommended when the output goes to the terminal or a command
substitution.
All subcommands also accept a -z or --null-in switch, which makes them
accept arguments from stdin separated with NULL-bytes. Since Unix paths
can't contain NULL, that makes it possible to handle all possible paths
and read input from e.g. find -print0. If arguments are given on the
commandline this has no effect. This should mostly be unnecessary since
path automatically starts splitting on NULL if one appears in the first
PATH_MAX bytes, PATH_MAX being the operating system's maximum length
for a path plus a NULL byte.
Some subcommands operate on the paths as strings and so work on
nonexistent paths, while others need to access the paths themselves and
so filter out nonexistent paths.
The following subcommands are available.
"basename" subcommand
path basename [-E | --no-extension] [-z | --null-in] [-Z | --null-out] [-q | --quiet] [PATH ...]
path basename returns the last path component of the given path, by
removing the directory prefix and removing trailing slashes. In other
words, it is the part that is not the dirname. For files you might call
it the "filename".
If the -E or ---no-extension option is used and the base name contained
a period, the path is returned with the extension (or the last
extension) removed, i.e. the "filename" without an extension (akin to
calling path change-extension "" (path basename $path)).
It returns 0 if there was a basename, i.e. if the path wasn't empty or
just slashes.
Examples
>_ path basename ./foo.mp4
foo.mp4
>_ path basename ../banana
banana
>_ path basename /usr/bin/
bin
>_ path basename /usr/bin/*
# This prints all files in /usr/bin/
# A selection:
cp
fish
grep
rm
"dirname" subcommand
path dirname [-z | --null-in] [-Z | --null-out] [-q | --quiet] [PATH ...]
path dirname returns the dirname for the given path. This is the part
before the last "/", discounting trailing slashes. In other words, it
is the part that is not the basename (discounting superfluous slashes).
It returns 0 if there was a dirname, i.e. if the path wasn't empty or
just slashes.
Examples
>_ path dirname ./foo.mp4
.
>_ path dirname ../banana
..
>_ path dirname /usr/bin/
/usr
"extension" subcommand
path extension [-z | --null-in] [-Z | --null-out] [-q | --quiet] [PATH ...]
path extension returns the extension of the given path. This is the
part after (and including) the last ".", unless that "." followed a "/"
or the basename is "." or "..", in which case there is no extension and
an empty line is printed.
If the filename ends in a ".", only a "." is printed.
It returns 0 if there was an extension.
Examples
>_ path extension ./foo.mp4
.mp4
>_ path extension ../banana
# an empty line, status 1
>_ path extension ~/.config
# an empty line, status 1
>_ path extension ~/.config.d
.d
>_ path extension ~/.config.
.
>_ set -l path (path change-extension '' ./foo.mp4)
>_ set -l extension (path extension ./foo.mp4)
> echo $path$extension
# reconstructs the original path again.
./foo.mp4
"filter" subcommand
path filter [-z | --null-in] [-Z | --null-out] [-q | --quiet] \
[-d] [-f] [-l] [-r] [-w] [-x] \
[-v | --invert] [(-t | --type) TYPE] [(-p | --perm) PERMISSION] [PATH ...]
path filter returns all of the given paths that match the given checks.
In all cases, the paths need to exist, nonexistent paths are always
filtered.
The available filters are:
o -t or --type with the options: "dir", "file", "link", "block",
"char", "fifo" and "socket", in which case the path needs to be a
directory, file, link, block device, character device, named pipe or
socket, respectively.
o -d, -f and -l are short for --type=dir, --type=file and --type=link,
respectively. There are no shortcuts for the other types.
o -p or --perm with the options: "read", "write", and "exec", as well
as "suid", "sgid", "user" (referring to the path owner) and "group"
(referring to the path's group), in which case the path needs to have
all of the given permissions for the current user.
o -r, -w and -x are short for --perm=read, --perm=write and
--perm=exec, respectively. There are no shortcuts for the other
permissions.
Note that the path needs to be any of the given types, but have all of
the given permissions. This is because having a path that is both
writable and executable makes sense, but having a path that is both a
directory and a file doesn't. Links will count as the type of the
linked-to file, so links to files count as files, links to directories
count as directories.
The filter options can either be given as multiple options, or
comma-separated - path filter -t dir,file or path filter --type dir
--type file are equivalent.
With --invert, the meaning of the filtering is inverted - any path that
wouldn't pass (including by not existing) passes, and any path that
would pass fails.
When a path starts with -, path filter will prepend ./ to avoid it
being interpreted as an option otherwise.
It returns 0 if at least one path passed the filter.
path is is shorthand for path filter -q, i.e. just checking without
producing output, see The is subcommand.
Examples
>_ path filter /usr/bin /usr/argagagji
# The (hopefully) nonexistent argagagji is filtered implicitly:
/usr/bin
>_ path filter --type file /usr/bin /usr/bin/fish
# Only fish is a file
/usr/bin/fish
>_ path filter --type file,dir --perm exec,write /usr/bin/fish /home/me
# fish is a file, which passes, and executable, which passes,
# but probably not writable, which fails.
#
# $HOME is a directory and both writable and executable, typically.
# So it passes.
/home/me
>_ path filter -fdxw /usr/bin/fish /home/me
# This is the same as above: "-f" is "--type=file", "-d" is "--type=dir",
# "-x" is short for "--perm=exec" and "-w" short for "--perm=write"!
/home/me
>_ path filter -fx $PATH/*
# Prints all possible commands - the first entry of each name is what fish would execute!
"is" subcommand
path is [-z | --null-in] [-Z | --null-out] [-q | --quiet] \
[-d] [-f] [-l] [-r] [-w] [-x] \
[-v | --invert] [(-t | --type) TYPE] [(-p | --perm) PERMISSION] [PATH ...]
path is is short for path filter -q. It returns true if any of the
given files passes the filter, but does not produce any output.
--quiet can still be passed for compatibility but is redundant. The
options are the same as for path filter.
Examples
>_ path is /usr/bin /usr/argagagji
# /usr/bin exists, so this returns a status of 0 (true). It prints nothing.
>_ path is /usr/argagagji
# /usr/argagagji does not, so this returns a status of 1 (false). It also prints nothing.
>_ path is -fx /bin/sh
# /bin/sh is usually an executable file, so this returns true.
"mtime" subcommand
path mtime [-z | --null-in] [-Z | --null-out] [-q | --quiet] [-R | --relative] [PATH ...]
path mtime returns the last modification time ("mtime" in unix jargon)
of the given paths, in seconds since the unix epoch (the beginning of
the 1st of January 1970).
With --relative (or -R), it prints the number of seconds since the
modification time. It only reads the current time once at start, so in
case multiple paths are given the times are all relative to the start
of path mtime -R running.
If you want to know if a file is newer or older than another file,
consider using test -nt instead. See the test documentation.
It returns 0 if reading mtime for any path succeeded.
Examples
>_ date +%s
# This prints the current time as seconds since the epoch
1657217847
>_ path mtime /etc/
1657213796
>_ path mtime -R /etc/
4078
# So /etc/ on this system was last modified a little over an hour ago
# This is the same as
>_ math (date +%s) - (path mtime /etc/)
"normalize" subcommand
path normalize [-z | --null-in] [-Z | --null-out] [-q | --quiet] [PATH ...]
path normalize returns the normalized versions of all paths. That means
it squashes duplicate "/", collapses "../" with earlier components and
removes "." components.
Unlike realpath or path resolve, it does not make the paths absolute.
It also does not resolve any symlinks. As such it can operate on
non-existent paths.
Because it operates on paths as strings and doesn't resolve symlinks,
it works sort of like pwd -L and cd. E.g. path normalize link/.. will
return ., just like cd link; cd .. would return to the current
directory. For a physical view of the filesystem, see path resolve.
Leading "./" components are usually removed. But when a path starts
with -, path normalize will add it instead to avoid confusion with
options.
It returns 0 if any normalization was done, i.e. any given path wasn't
in canonical form.
Examples
>_ path normalize /usr/bin//../../etc/fish
# The "//" is squashed and the ".." components neutralize the components before
/etc/fish
>_ path normalize /bin//bash
# The "//" is squashed, but /bin isn't resolved even if your system links it to /usr/bin.
/bin/bash
>_ path normalize ./my/subdirs/../sub2
my/sub2
>_ path normalize -- -/foo
./-/foo
"resolve" subcommand
path resolve [-z | --null-in] [-Z | --null-out] [-q | --quiet] [PATH ...]
path resolve returns the normalized, physical and absolute versions of
all paths. That means it resolves symlinks and does what path normalize
does: it squashes duplicate "/", collapses "../" with earlier
components and removes "." components. Then it turns that path into the
absolute path starting from the filesystem root "/".
It is similar to realpath, as it creates the "real", canonical version
of the path. However, for paths that can't be resolved, e.g. if they
don't exist or form a symlink loop, it will resolve as far as it can
and normalize the rest.
Because it resolves symlinks, it works sort of like pwd -P. E.g. path
resolve link/.. will return the parent directory of what the link
points to, just like cd link; cd (pwd -P)/.. would go to it. For a
logical view of the filesystem, see path normalize.
It returns 0 if any normalization or resolution was done, i.e. any
given path wasn't in canonical form.
Examples
>_ path resolve /bin//sh
# The "//" is squashed, and /bin is resolved if your system links it to /usr/bin.
# sh here is bash (this is common on linux systems)
/usr/bin/bash
>_ path resolve /bin/foo///bar/../baz
# Assuming /bin exists and is a symlink to /usr/bin, but /bin/foo doesn't.
# This resolves the /bin/ and normalizes the nonexistent rest:
/usr/bin/foo/baz
"change-extension" subcommand
path change-extension [-z | --null-in] [-Z | --null-out] \
[-q | --quiet] EXTENSION [PATH ...]
path change-extension returns the given paths, with their extension
changed to the given new extension. The extension is the part after
(and including) the last ".", unless that "." followed a "/" or the
basename is "." or "..", in which case there is no previous extension
and the new one is simply added.
If the extension is empty, any previous extension is stripped, along
with the ".". This is, of course, the inverse of path extension.
One leading dot on the extension is ignored, so ".mp3" and "mp3" are
treated the same.
It returns 0 if it was given any paths.
Examples
>_ path change-extension mp4 ./foo.wmv
./foo.mp4
>_ path change-extension .mp4 ./foo.wmv
./foo.mp4
>_ path change-extension '' ../banana
../banana
>_ path change-extension '' ~/.config
/home/alfa/.config
>_ path change-extension '' ~/.config.d
/home/alfa/.config
>_ path change-extension '' ~/.config.
/home/alfa/.config
"sort" subcommand
path sort [-z | --null-in] [-Z | --null-out] \
[-q | --quiet] [-r | --reverse] \
[--key=basename|dirname|path] [PATH ...]
path sort returns the given paths in sorted order. They are sorted in
the same order as globs - alphabetically, but with runs of numerical
digits compared numerically.
With --reverse or -r the sort is reversed.
With --key= only the given part of the path is compared, e.g.
--key=dirname causes only the dirname to be compared, --key=basename
only the basename and --key=path causes the entire path to be compared
(this is the default).
With --unique or -u the sort is deduplicated, meaning only the first of
a run that have the same key is kept. So if you are sorting by
basename, then only the first of each basename is used.
The sort used is stable, so sorting first by basename and then by
dirname works and causes the files to be grouped according to
directory.
It currently returns 0 if it was given any paths.
Examples
>_ path sort 10-foo 2-bar
2-bar
10-foo
>_ path sort --reverse 10-foo 2-bar
10-foo
2-bar
>_ path sort --unique --key=basename $fish_function_path/*.fish
# prints a list of all function files fish would use, sorted by name.
Combining path
path is meant to be easy to combine with itself, other tools and fish.
This is why
o path's output is automatically split by fish if it goes into a
command substitution, so just doing (path ...) handles all paths,
even those containing newlines, correctly
o path has --null-in to handle null-delimited input (typically
automatically detected!), and --null-out to pass on null-delimited
output
Some examples of combining path:
# Expand all paths in the current directory, leave only executable files, and print their resolved path
path filter -zZ -xf -- * | path resolve -z
# The same thing, but using find (note -maxdepth needs to come first or find will scream)
# (this also depends on your particular version of find)
# Note the `-z` is unnecessary for any sensible version of find - if `path` sees a NULL,
# it will split on NULL automatically.
find . -maxdepth 1 -type f -executable -print0 | path resolve -z
set -l paths (path filter -p exec $PATH/fish -Z | path resolve)
popd - move through directory stack
Synopsis
popd
Description
popd removes the top directory from the directory stack and changes the
working directory to the new top directory. Use pushd to add
directories to the stack.
The -h or --help option displays help about using this command.
Example
pushd /usr/src
# Working directory is now /usr/src
# Directory stack contains /usr/src
pushd /usr/src/fish-shell
# Working directory is now /usr/src/fish-shell
# Directory stack contains /usr/src /usr/src/fish-shell
popd
# Working directory is now /usr/src
# Directory stack contains /usr/src
See Also
o the dirs command to print the directory stack
o the cdh command which provides a more intuitive way to navigate to
recently visited directories.
prevd - move backward through directory history
Synopsis
prevd [-l | --list] [POS]
Description
prevd moves backwards POS positions in the history of visited
directories; if the beginning of the history has been hit, a warning is
printed.
If the -l or --list flag is specified, the current history is also
displayed.
Note that the cd command limits directory history to the 25 most
recently visited directories. The history is stored in the dirprev and
dirnext variables which this command manipulates.
The -h or --help option displays help about using this command.
Example
cd /usr/src
# Working directory is now /usr/src
cd /usr/src/fish-shell
# Working directory is now /usr/src/fish-shell
prevd
# Working directory is now /usr/src
nextd
# Working directory is now /usr/src/fish-shell
See Also
o the cdh command to display a prompt to quickly navigate the history
o the dirh command to print the directory history
o the nextd command to move forward
printf - display text according to a format string
Synopsis
printf FORMAT [ARGUMENT ...]
Description
NOTE: This page documents the fish builtin printf. To see the
documentation on any non-fish versions, use command man printf.
printf uses the format string FORMAT to print the ARGUMENT arguments.
This means that it takes format specifiers in the format string and
replaces each with an argument.
The FORMAT argument is re-used as many times as necessary to convert
all of the given arguments. So printf %s\n flounder catfish clownfish
shark will print four lines.
Unlike echo, printf does not append a new line unless it is specified
as part of the string.
It doesn't support any options, so there is no need for a -- separator,
which makes it easier to use for arbitrary input than echo. [1]
Format Specifiers
Valid format specifiers are taken from the C library function
printf(3):
o %d or %i: Argument will be used as decimal integer (signed or
unsigned)
o %o: An octal unsigned integer
o %u: An unsigned decimal integer - this means negative numbers will
wrap around
o %x or %X: An unsigned hexadecimal integer
o %f, %g or %G: A floating-point number. %f defaults to 6 places after
the decimal point (which is locale-dependent - e.g. in de_DE it will
be a ,). %g and %G will trim trailing zeroes and switch to scientific
notation (like %e) if the numbers get small or large enough.
o %e or %E: A floating-point number in scientific (XXXeYY) notation
o %s: A string
o %b: As a string, interpreting backslash escapes, except that octal
escapes are of the form 0 or 0ooo.
%% signifies a literal "%".
Conversion can fail, e.g. "102.234" can't losslessly convert to an
integer, causing printf to print an error. If you are okay with losing
information, silence errors with 2>/dev/null.
A number between the % and the format letter specifies the width. The
result will be left-padded with spaces.
Backslash Escapes
printf also knows a number of backslash escapes:
o \" double quote
o \\ backslash
o \a alert (bell)
o \b backspace
o \c produce no further output
o \e escape
o \f form feed
o \n new line
o \r carriage return
o \t horizontal tab
o \v vertical tab
o \ooo octal number (ooo is 1 to 3 digits)
o \xhh hexadecimal number (hhh is 1 to 2 digits)
o \uhhhh 16-bit Unicode character (hhhh is 4 digits)
o \Uhhhhhhhh 32-bit Unicode character (hhhhhhhh is 8 digits)
Errors and Return Status
If the given argument doesn't work for the given format (like when you
try to convert a number like 3.141592 to an integer), printf prints an
error, to stderr. printf will then also return non-zero, but will still
try to print as much as it can.
It will also return non-zero if no argument at all was given, in which
case it will print nothing.
This printf has been imported from the printf in GNU Coreutils version
6.9. If you would like to use a newer version of printf, for example
the one shipped with your OS, try command printf.
Example
printf '%s\t%s\n' flounder fish
Will print "flounder fish" (separated with a tab character),
followed by a newline character. This is useful for writing
completions, as fish expects completion scripts to output the option
followed by the description, separated with a tab character.
printf '%s: %d' "Number of bananas in my pocket" 42
Will print "Number of bananas in my pocket: 42", without a newline.
See Also
o the echo command, for simpler output
Footnotes
[1] In fact, while fish's echo supports --, POSIX forbids it, so other
implementations can't be used if the input contains anything
starting with -.
prompt_hostname - print the hostname, shortened for use in the prompt
Synopsis
prompt_hostname
Description
prompt_hostname prints a shortened version the current hostname for use
in the prompt. It will print just the first component of the hostname,
everything up to the first dot.
Examples
function fish_prompt
echo -n (whoami)@(prompt_hostname) (prompt_pwd) '$ '
end
# The machine's full hostname is foo.bar.com
>_ prompt_hostname
foo
prompt_login - describe the login suitable for prompt
Synopsis
prompt_login
Description
prompt_login is a function to describe the current login. It will show
the user, the host and also whether the shell is running in a chroot
(currently Debian's debian_chroot file is supported).
Examples
function fish_prompt
echo -n (prompt_login) (prompt_pwd) '$ '
end
>_ prompt_login
root@bananablaster
prompt_pwd - print pwd suitable for prompt
Synopsis
prompt_pwd
Description
prompt_pwd is a function to print the current working directory in a
way suitable for prompts. It will replace the home directory with "~"
and shorten every path component but the last to a default of one
character.
To change the number of characters per path component, pass
--dir-length= or set fish_prompt_pwd_dir_length to the number of
characters. Setting it to 0 or an invalid value will disable shortening
entirely. This defaults to 1.
To keep some components unshortened, pass --full-length-dirs= or set
fish_prompt_pwd_full_dirs to the number of components. This defaults to
1, keeping the last component.
If any positional arguments are given, prompt_pwd shortens them instead
of PWD.
Options
-d or --dir-length MAX
Causes the components to be shortened to MAX characters each.
This overrides fish_prompt_pwd_dir_length.
-D or --full-length-dirs NUM
Keeps NUM components (counted from the right) as full length
without shortening. This overrides fish_prompt_pwd_full_dirs.
-h or --help
Displays help about using this command.
Examples
>_ cd ~/
>_ echo $PWD
/home/alfa
>_ prompt_pwd
~
>_ cd /tmp/banana/sausage/with/mustard
>_ prompt_pwd
/t/b/s/w/mustard
>_ set -g fish_prompt_pwd_dir_length 3
>_ prompt_pwd
/tmp/ban/sau/wit/mustard
>_ prompt_pwd --full-length-dirs=2 --dir-length=1
/t/b/s/with/mustard
psub - perform process substitution
Synopsis
COMMAND1 ( COMMAND2 | psub [-F | --fifo] [-f | --file] [(-s | --suffix) SUFFIX] )
Description
Some shells (e.g., ksh, bash) feature a syntax that is a mix between
command substitution and piping, called process substitution. It is
used to send the output of a command into the calling command, much
like command substitution, but with the difference that the output is
not sent through commandline arguments but through a named pipe, with
the filename of the named pipe sent as an argument to the calling
program. psub combined with a regular command substitution provides the
same functionality.
The following options are available:
-f or --file
Use a regular file instead of a named pipe to communicate with
the calling process. This will cause psub to be significantly
slower when large amounts of data are involved, but has the
advantage that the reading process can seek in the stream. This
is the default.
-F or --fifo
Use a named pipe rather than a file. You should only use this if
the command produces no more than 8 KiB of output. The limit on
the amount of data a FIFO can buffer varies with the OS but is
typically 8 KiB, 16 KiB or 64 KiB. If you use this option and
the command on the left of the psub pipeline produces more
output a deadlock is likely to occur.
-s or --suffix SUFFIX
Append SUFFIX to the filename.
-h or --help
Displays help about using this command.
Example
diff (sort a.txt | psub) (sort b.txt | psub)
# shows the difference between the sorted versions of files ``a.txt`` and ``b.txt``.
source-highlight -f esc (cpp main.c | psub -f -s .c)
# highlights ``main.c`` after preprocessing as a C source.
pushd - push directory to directory stack
Synopsis
pushd DIRECTORY
Description
The pushd function adds DIRECTORY to the top of the directory stack and
makes it the current working directory. popd will pop it off and return
to the original directory.
Without arguments, it exchanges the top two directories in the stack.
pushd +NUMBER rotates the stack counter-clockwise i.e. from bottom to
top
pushd -NUMBER rotates clockwise i.e. top to bottom.
The -h or --help option displays help about using this command.
Example
cd ~/dir1
pushd ~/dir2
pushd ~/dir3
# Working directory is now ~/dir3
# Directory stack contains ~/dir2 ~/dir1
pushd /tmp
# Working directory is now /tmp
# Directory stack contains ~/dir3 ~/dir2 ~/dir1
pushd +1
# Working directory is now ~/dir3
# Directory stack contains ~/dir2 ~/dir1 /tmp
popd
# Working directory is now ~/dir2
# Directory stack contains ~/dir1 /tmp
See Also
o the dirs command to print the directory stack
o the cdh command which provides a more intuitive way to navigate to
recently visited directories.
pwd - output the current working directory
Synopsis
pwd [-P | --physical]
pwd [-L | --logical]
Description
NOTE: This page documents the fish builtin pwd. To see the
documentation on any non-fish versions, use command man pwd.
pwd outputs (prints) the current working directory.
The following options are available:
-L or --logical
Output the logical working directory, without resolving symlinks
(default behavior).
-P or --physical
Output the physical working directory, with symlinks resolved.
-h or --help
Displays help about using this command.
See Also
Navigate directories using the directory history or the directory stack
random - generate random number
Synopsis
random
random SEED
random START END
random START STEP END
random choice [ITEMS ...]
Description
random generates a pseudo-random integer from a uniform distribution.
The range (inclusive) depends on the arguments.
No arguments indicate a range of 0 to 32767 (inclusive).
If one argument is specified, the internal engine will be seeded with
the argument for future invocations of random and no output will be
produced.
Two arguments indicate a range from START to END (both START and END
included).
Three arguments indicate a range from START to END with a spacing of
STEP between possible outputs.
random choice will select one random item from the succeeding
arguments.
The -h or --help option displays help about using this command.
Note that seeding the engine will NOT give the same result across
different systems.
You should not consider random cryptographically secure, or even
statistically accurate.
Example
The following code will count down from a random even number between 10
and 20 to 1:
for i in (seq (random 10 2 20) -1 1)
echo $i
end
And this will open a random picture from any of the subdirectories:
open (random choice **.jpg)
Or, to only get even numbers from 2 to 20:
random 2 2 20
Or odd numbers from 1 to 3:
random 1 2 3 # or 1 2 4
read - read line of input into variables
Synopsis
read [OPTIONS] [VARIABLE ...]
Description
NOTE: This page documents the fish builtin read. To see the
documentation on any non-fish versions, use command man read.
read reads from standard input and stores the result in shell
variables. In an alternative mode, it can also print to its own
standard output, for example for use in command substitutions.
By default, read reads a single line and splits it into variables on
spaces or tabs. Alternatively, a null character or a maximum number of
characters can be used to terminate the input, and other delimiters can
be given.
Unlike other shells, there is no default variable (such as REPLY) for
storing the result - instead, it is printed on standard output.
When read reaches the end-of-file (EOF) instead of the terminator, the
exit status is set to 1. Otherwise, it is set to 0.
If read sets a variable and you don't specify a scope, it will use the
same rules that set - display and change shell variables does - if the
variable exists, it will use it (in the lowest scope). If it doesn't,
it will use an unexported function-scoped variable.
The following options, like the corresponding ones in set - display and
change shell variables, control variable scope or attributes:
-U or --universal
Sets a universal variable. The variable will be immediately
available to all the user's fish instances on the machine, and
will be persisted across restarts of the shell.
-f or --function
Sets a variable scoped to the executing function. It is erased
when the function ends.
-l or --local
Sets a locally-scoped variable in this block. It is erased when
the block ends. Outside of a block, this is the same as
--function.
-g or --global
Sets a globally-scoped variable. Global variables are available
to all functions running in the same shell. They can be
modified or erased.
-u or --unexport
Prevents the variables from being exported to child processes
(default behaviour).
-x or --export
Exports the variables to child processes.
The following options control the interactive mode:
-c CMD or --command CMD
Sets the initial string in the interactive mode command buffer
to CMD.
-s or --silent
Masks characters written to the terminal, replacing them with
asterisks. This is useful for reading things like passwords or
other sensitive information.
-p or --prompt PROMPT_CMD
Uses the output of the shell command PROMPT_CMD as the prompt
for the interactive mode. The default prompt command is
set_color green; echo -n read; set_color normal; echo -n "> "
-P or --prompt-str PROMPT_STR
Uses the literal PROMPT_STR as the prompt for the interactive
mode.
-R or --right-prompt RIGHT_PROMPT_CMD
Uses the output of the shell command RIGHT_PROMPT_CMD as the
right prompt for the interactive mode. There is no default right
prompt command.
-S or --shell
Enables syntax highlighting, tab completions and command
termination suitable for entering shellscript code in the
interactive mode. NOTE: Prior to fish 3.0, the short opt for
--shell was -s, but it has been changed for compatibility with
bash's -s short opt for --silent.
The following options control how much is read and how it is stored:
-d or --delimiter DELIMITER
Splits on DELIMITER. DELIMITER will be used as an entire string
to split on, not a set of characters.
-n or --nchars NCHARS
Makes read return after reading NCHARS characters or the end of
the line, whichever comes first.
-t -or --tokenize
Causes read to split the input into variables by the shell's
tokenization rules. This means it will honor quotes and
escaping. This option is of course incompatible with other
options to control splitting like --delimiter and does not honor
IFS (like fish's tokenizer). It saves the tokens in the manner
they'd be passed to commands on the commandline, so e.g. a\ b is
stored as a b. Note that currently it leaves command
substitutions intact along with the parentheses.
-a or --list
Stores the result as a list in a single variable. This option is
also available as --array for backwards compatibility.
-z or --null
Marks the end of the line with the NUL character, instead of
newline. This also disables interactive mode.
-L or --line
Reads each line into successive variables, and stops after each
variable has been filled. This cannot be combined with the
--delimiter option.
Without the --line option, read reads a single line of input from
standard input, breaks it into tokens, and then assigns one token to
each variable specified in VARIABLES. If there are more tokens than
variables, the complete remainder is assigned to the last variable.
If no option to determine how to split like --delimiter, --line or
--tokenize is given, the variable IFS is used as a list of characters
to split on. Relying on the use of IFS is deprecated and this behaviour
will be removed in future versions. The default value of IFS contains
space, tab and newline characters. As a special case, if IFS is set to
the empty string, each character of the input is considered a separate
token.
With the --line option, read reads a line of input from standard input
into each provided variable, stopping when each variable has been
filled. The line is not tokenized.
If no variable names are provided, read enters a special case that
simply provides redirection from standard input to standard output,
useful for command substitution. For instance, the fish shell command
below can be used to read a password from the console instead of
hardcoding it in the command itself, which prevents it from showing up
in fish's history:
mysql -uuser -p(read)
When running in this mode, read does not split the input in any way and
text is redirected to standard output without any further processing or
manipulation.
If -l or --list is provided, only one variable name is allowed and the
tokens are stored as a list in this variable.
In order to protect the shell from consuming too many system resources,
read will only consume a maximum of 100 MiB (104857600 bytes); if the
terminator is not reached before this limit then VARIABLE is set to
empty and the exit status is set to 122. This limit can be altered with
the fish_read_limit variable. If set to 0 (zero), the limit is removed.
Example
read has a few separate uses.
The following code stores the value 'hello' in the shell variable foo.
echo hello | read foo
The while command is a neat way to handle command output line-by-line:
printf '%s\n' line1 line2 line3 line4 | while read -l foo
echo "This is another line: $foo"
end
Delimiters given via "-d" are taken as one string:
echo a==b==c | read -d == -l a b c
echo $a # a
echo $b # b
echo $c # c
--tokenize honors quotes and escaping like the shell's argument
passing:
echo 'a\ b' | read -t first second
echo $first # outputs "a b", $second is empty
echo 'a"foo bar"b (command echo wurst)*" "{a,b}' | read -lt -l a b c
echo $a # outputs 'afoo barb' (without the quotes)
echo $b # outputs '(command echo wurst)* {a,b}' (without the quotes)
echo $c # nothing
For an example on interactive use, see Querying for user input.
realpath - convert a path to an absolute path without symlinks
Synopsis
realpath [OPTIONS] PATH
Description
NOTE: This page documents the fish builtin realpath. To see the
documentation on any non-fish versions, use command man realpath.
realpath follows all symbolic links encountered for the provided PATH,
printing the absolute path resolved. fish provides a realpath-alike
builtin intended to enrich systems where no such command is installed
by default.
If a realpath command exists, that will be preferred. builtin realpath
will explicitly use the fish implementation of realpath.
The following options are available:
-s or --no-symlinks
Don't resolve symlinks, only make paths absolute, squash
multiple slashes and remove trailing slashes.
-h or --help
Displays help about using this command.
return - stop the current inner function
Synopsis
return [N]
Description
return halts a currently running function. The exit status is set to N
if it is given. If return is invoked outside of a function or dot
script it is equivalent to exit.
It is often added inside of a conditional block such as an if statement
or a switch statement to conditionally stop the executing function and
return to the caller; it can also be used to specify the exit status of
a function.
If at the top level of a script, it exits with the given status, like
exit. If at the top level in an interactive session, it will set
status, but not exit the shell.
The -h or --help option displays help about using this command.
Example
An implementation of the false command as a fish function:
function false
return 1
end
set - display and change shell variables
Synopsis
set
set (-f | --function) (-l | --local) (-g | --global) (-U | --universal) [--no-event]
set [-Uflg] NAME [VALUE ...]
set [-Uflg] NAME[[INDEX ...]] [VALUE ...]
set (-x | --export) (-u | --unexport) [-Uflg] NAME [VALUE ...]
set (-a | --append) (-p | --prepend) [-Uflg] NAME VALUE ...
set (-q | --query) (-e | --erase) [-Uflg] [NAME][[INDEX]] ...]
set (-S | --show) (-L | --long) [NAME ...]
Description
set manipulates shell variables.
If both NAME and VALUE are provided, set assigns any values to variable
NAME. Variables in fish are lists, multiple values are allowed. One
or more variable INDEX can be specified including ranges (not for all
options.)
If no VALUE is given, the variable will be set to the empty list.
If set is ran without arguments, it prints the names and values of all
shell variables in sorted order. Passing scope or export flags allows
filtering this to only matching variables, so set --local would only
show local variables.
With --erase and optionally a scope flag set will erase the matching
variable (or the variable of that name in the smallest possible scope).
With --show, set will describe the given variable names, explaining how
they have been defined - in which scope with which values and options.
The following options control variable scope:
-U or --universal
Sets a universal variable. The variable will be immediately
available to all the user's fish instances on the machine, and
will be persisted across restarts of the shell.
-f or --function
Sets a variable scoped to the executing function. It is erased
when the function ends.
-l or --local
Sets a locally-scoped variable in this block. It is erased when
the block ends. Outside of a block, this is the same as
--function.
-g or --global
Sets a globally-scoped variable. Global variables are available
to all functions running in the same shell. They can be
modified or erased.
These options modify how variables operate:
--export or -x
Causes the specified shell variable to be exported to child
processes (making it an "environment variable").
--unexport or -u
Causes the specified shell variable to NOT be exported to child
processes.
--path Treat specified variable as a path variable; variable will be
split on colons (:) and will be displayed joined by colons when
quoted (echo "$PATH") or exported.
--unpath
Causes variable to no longer be treated as a path variable.
Note: variables ending in "PATH" are automatically path
variables.
Further options:
-a or --append NAME VALUE ...
Appends VALUES to the current set of values for variable NAME.
Can be used with --prepend to both append and prepend at the
same time. This cannot be used when assigning to a variable
slice.
-p or --prepend NAME VALUE ...
Prepends VALUES to the current set of values for variable NAME.
This can be used with --append to both append and prepend at the
same time. This cannot be used when assigning to a variable
slice.
-e or --erase NAME[INDEX]
Causes the specified shell variables to be erased. Supports
erasing from multiple scopes at once. Individual items in a
variable at INDEX in brackets can be specified.
-q or --query NAME[INDEX]
Test if the specified variable names are defined. If an INDEX
is provided, check for items at that slot. Does not output
anything, but the shell status is set to the number of variables
specified that were not defined, up to a maximum of 255. If no
variable was given, it also returns 255.
-n or --names
List only the names of all defined variables, not their value.
The names are guaranteed to be sorted.
-S or --show
Shows information about the given variables. If no variable
names are given then all variables are shown in sorted order.
It shows the scopes the given variables are set in, along with
the values in each and whether or not it is exported. No other
flags can be used with this option.
--no-event
Don't generate a variable change event when setting or erasing a
variable. We recommend using this carefully because the event
handlers are usually set up for a reason. Possible uses include
modifying the variable inside a variable handler.
-L or --long
Do not abbreviate long values when printing set variables.
-h or --help
Displays help about using this command.
If a variable is set to more than one value, the variable will be a
list with the specified elements. If a variable is set to zero
elements, it will become a list with zero elements.
If the variable name is one or more list elements, such as PATH[1 3 7],
only those list elements specified will be changed. If you specify a
negative index when expanding or assigning to a list variable, the
index will be calculated from the end of the list. For example, the
index -1 means the last index of a list.
The scoping rules when creating or updating a variable are:
o Variables may be explicitly set as universal, global, function, or
local. Variables with the same name but in a different scope will
not be changed.
o If the scope of a variable is not explicitly set but a variable by
that name has been previously defined, the scope of the existing
variable is used. If the variable is already defined in multiple
scopes, the variable with the narrowest scope will be updated.
o If a variable's scope is not explicitly set and there is no existing
variable by that name, the variable will be local to the currently
executing function. Note that this is different from using the -l or
--local flag, in which case the variable will be local to the
most-inner currently executing block, while without them the variable
will be local to the function as a whole. If no function is
executing, the variable will be set in the global scope.
The exporting rules when creating or updating a variable are identical
to the scoping rules for variables:
o Variables may be explicitly set to either exported or not exported.
When an exported variable goes out of scope, it is unexported.
o If a variable is not explicitly set to be exported or not exported,
but has been previously defined, the previous exporting rule for the
variable is kept.
o If a variable is not explicitly set to be either exported or
unexported and has never before been defined, the variable will not
be exported.
In query mode, the scope to be examined can be specified. Whether the
variable has to be a path variable or exported can also be specified.
In erase mode, if variable indices are specified, only the specified
slices of the list variable will be erased.
set requires all options to come before any other arguments. For
example, set flags -l will have the effect of setting the value of the
variable flags to '-l', not making the variable local.
Exit status
In assignment mode, set does not modify the exit status, but passes
along whatever status was set, including by command substitutions.
This allows capturing the output and exit status of a subcommand, like
in if set output (command).
In query mode, the exit status is the number of variables that were not
found.
In erase mode, set exits with a zero exit status in case of success,
with a non-zero exit status if the commandline was invalid, if any of
the variables did not exist or was a special read-only variable.
Examples
Print all global, exported variables:
> set -gx
Set the value of the variable _$foo_ to be 'hi'.:
> set foo hi
Append the value "there" to the variable $foo:
> set -a foo there
Remove _$smurf_ from the scope:
> set -e smurf
Remove _$smurf_ from the global and universal scopes:
> set -e -Ug smurf
Change the fourth element of the $PATH list to ~/bin:
> set PATH[4] ~/bin
Outputs the path to Python if type -p returns true:
if set python_path (type -p python)
echo "Python is at $python_path"
end
Setting a variable doesn't modify $status; a command substitution still
will, though:
> echo $status
0
> false
> set foo bar
> echo $status
1
> true
> set foo banana (false)
> echo $status
1
VAR=VALUE command sets a variable for just one command, like other
shells. This runs fish with a temporary home directory:
> HOME=(mktemp -d) fish
(which is essentially the same as):
> begin; set -lx HOME (mktemp -d); fish; end
Notes
o Fish versions prior to 3.0 supported the syntax set PATH[1] PATH[4]
/bin /sbin, which worked like set PATH[1 4] /bin /sbin.
set_color - set the terminal color
Synopsis
set_color [OPTIONS] VALUE
Description
set_color is used to control the color and styling of text in the
terminal. VALUE describes that styling. VALUE can be a reserved color
name like red or an RGB color value given as 3 or 6 hexadecimal digits
("F27" or "FF2277"). A special keyword normal resets text formatting to
terminal defaults.
Valid colors include:
o black, red, green, yellow, blue, magenta, cyan, white
o brblack, brred, brgreen, bryellow, brblue, brmagenta, brcyan,
brwhite
The br- (as in 'bright') forms are full-brightness variants of the 8
standard-brightness colors on many terminals. brblack has higher
brightness than black - towards gray.
An RGB value with three or six hex digits, such as A0FF33 or f2f can be
used. Fish will choose the closest supported color. A three digit value
is equivalent to specifying each digit twice; e.g., set_color 2BC is
the same as set_color 22BBCC. Hexadecimal RGB values can be in lower or
uppercase. Depending on the capabilities of your terminal (and the
level of support set_color has for it) the actual color may be
approximated by a nearby matching reserved color name or set_color may
not have an effect on color.
A second color may be given as a desired fallback color. e.g. set_color
124212 brblue will instruct set_color to use brblue if a terminal is
not capable of the exact shade of grey desired. This is very useful
when an 8 or 16 color terminal might otherwise not use a color.
The following options are available:
-b or --background COLOR
Sets the background color.
-c or --print-colors
Prints the given colors or a colored list of the 16 named
colors.
-o or --bold
Sets bold mode.
-d or --dim
Sets dim mode.
-i or --italics
Sets italics mode.
-r or --reverse
Sets reverse mode.
-u or --underline
Sets underlined mode.
-h or --help
Displays help about using this command.
Using the normal keyword will reset foreground, background, and all
formatting back to default.
Notes
1. Using the normal keyword will reset both background and foreground
colors to whatever is the default for the terminal.
2. Setting the background color only affects subsequently written
characters. Fish provides no way to set the background color for the
entire terminal window. Configuring the window background color (and
other attributes such as its opacity) has to be done using whatever
mechanisms the terminal provides. Look for a config option.
3. Some terminals use the --bold escape sequence to switch to a
brighter color set rather than increasing the weight of text.
4. set_color works by printing sequences of characters to standard
output. If used in command substitution or a pipe, these characters
will also be captured. This may or may not be desirable. Checking
the exit status of isatty stdout before using set_color can be
useful to decide not to colorize output in a script.
Examples
set_color red; echo "Roses are red"
set_color blue; echo "Violets are blue"
set_color 62A; echo "Eggplants are dark purple"
set_color normal; echo "Normal is nice" # Resets the background too
Terminal Capability Detection
Fish uses some heuristics to determine what colors a terminal supports
to avoid sending sequences that it won't understand.
In particular it will:
o Enable 256 colors if TERM contains "xterm", except for known
exceptions (like MacOS 10.6 Terminal.app)
o Enable 24-bit ("true-color") even if the $TERM entry only reports 256
colors. This includes modern xterm, VTE-based terminals like Gnome
Terminal, Konsole and iTerm2.
o Detect support for italics, dim, reverse and other modes.
If terminfo reports 256 color support for a terminal, 256 color support
will always be enabled.
To force true-color support on or off, set fish_term24bit to "1" for on
and 0 for off - set -g fish_term24bit 1.
To debug color palette problems, tput colors may be useful to see the
number of colors in terminfo for a terminal. Fish launched as fish -d
term_support will include diagnostic messages that indicate the color
support mode in use.
The set_color command uses the terminfo database to look up how to
change terminal colors on whatever terminal is in use. Some systems
have old and incomplete terminfo databases, and lack color information
for terminals that support it. Fish assumes that all terminals can use
the ANSI X3.64 escape
sequences if the terminfo definition indicates a color below 16 is not
supported.
source - evaluate contents of file
Synopsis
source FILE [ARGUMENTS ...]
SOMECOMMAND | source
. FILE [ARGUMENTS ...]
Description
source evaluates the commands of the specified FILE in the current
shell as a new block of code. This is different from starting a new
process to perform the commands (i.e. fish < FILE) since the commands
will be evaluated by the current shell, which means that changes in
shell variables will affect the current shell. If additional arguments
are specified after the file name, they will be inserted into the argv
variable. The argv variable will not include the name of the sourced
file.
fish will search the working directory to resolve relative paths but
will not search PATH .
If no file is specified and a file or pipeline is connected to standard
input, or if the file name - is used, source will read from standard
input. If no file is specified and there is no redirected file or
pipeline on standard input, an error will be printed.
The exit status of source is the exit status of the last job to
execute. If something goes wrong while opening or reading the file,
source exits with a non-zero status.
Some other shells only support the . alias (a single period). The use
of . is deprecated in favour of source, and . will be removed in a
future version of fish.
source creates a new local scope; set --local within a sourced block
will not affect variables in the enclosing scope.
The -h or --help option displays help about using this command.
Example
source ~/.config/fish/config.fish
# Causes fish to re-read its initialization file.
Caveats
In fish versions prior to 2.3.0, the argv variable would have a single
element (the name of the sourced file) if no arguments are present.
Otherwise, it would contain arguments without the name of the sourced
file. That behavior was very confusing and unlike other shells such as
bash and zsh.
status - query fish runtime information
Synopsis
status
status is-login
status is-interactive
status is-block
status is-breakpoint
status is-command-substitution
status is-no-job-control
status is-full-job-control
status is-interactive-job-control
status current-command
status current-commandline
status filename
status basename
status dirname
status fish-path
status function
status line-number
status stack-trace
status job-control CONTROL_TYPE
status features
status test-feature FEATURE
status buildinfo
Description
With no arguments, status displays a summary of the current login and
job control status of the shell.
The following operations (subcommands) are available:
is-command-substitution, -c or --is-command-substitution
Returns 0 if fish is currently executing a command substitution.
is-block, -b or --is-block
Returns 0 if fish is currently executing a block of code.
is-breakpoint
Returns 0 if fish is currently showing a prompt in the context
of a breakpoint command. See also the fish_breakpoint_prompt
function.
is-interactive, -i or --is-interactive
Returns 0 if fish is interactive - that is, connected to a
keyboard.
is-login, -l or --is-login
Returns 0 if fish is a login shell - that is, if fish should
perform login tasks such as setting up PATH.
is-full-job-control or --is-full-job-control
Returns 0 if full job control is enabled.
is-interactive-job-control or --is-interactive-job-control
Returns 0 if interactive job control is enabled.
is-no-job-control or --is-no-job-control
Returns 0 if no job control is enabled.
current-command
Prints the name of the currently-running function or command,
like the deprecated _ variable.
current-commandline
Prints the entirety of the currently-running commandline,
inclusive of all jobs and operators.
filename, current-filename, -f or --current-filename
Prints the filename of the currently-running script. If the
current script was called via a symlink, this will return the
symlink. If the current script was received by piping into
source, then this will return -.
basename
Prints just the filename of the running script, without any path
components before.
dirname
Prints just the path to the running script, without the actual
filename itself. This can be relative to PWD (including just
"."), depending on how the script was called. This is the same
as passing the filename to dirname(3). It's useful if you want
to use other files in the current script's directory or similar.
fish-path
Prints the absolute path to the currently executing instance of
fish. This is a best-effort attempt and the exact output is down
to what the platform gives fish. In some cases you might only
get "fish".
function or current-function
Prints the name of the currently called function if able, when
missing displays "Not a function" (or equivalent translated
string).
line-number, current-line-number, -n or --current-line-number
Prints the line number of the currently running script.
stack-trace, print-stack-trace, -t or --print-stack-trace
Prints a stack trace of all function calls on the call stack.
job-control, -j or --job-control CONTROL_TYPE
Sets the job control type to CONTROL_TYPE, which can be none,
full, or interactive.
features
Lists all available feature flags.
test-feature FEATURE
Returns 0 when FEATURE is enabled, 1 if it is disabled, and 2 if
it is not recognized.
buildinfo
This prints information on how fish was build - which
architecture, which build system or profile was used, etc. This
is mainly useful for debugging.
Notes
For backwards compatibility most subcommands can also be specified as a
long or short option. For example, rather than status is-login you can
type status --is-login. The flag forms are deprecated and may be
removed in a future release (but not before fish 4.0).
You can only specify one subcommand per invocation even if you use the
flag form of the subcommand.
string - manipulate strings
Synopsis
string collect [-a | --allow-empty] [-N | --no-trim-newlines] [STRING ...]
string escape [-n | --no-quoted] [--style=] [STRING ...]
string join [-q | --quiet] [-n | --no-empty] SEP [STRING ...]
string join0 [-q | --quiet] [STRING ...]
string length [-q | --quiet] [STRING ...]
string lower [-q | --quiet] [STRING ...]
string match [-a | --all] [-e | --entire] [-i | --ignore-case]
[-g | --groups-only] [-r | --regex] [-n | --index]
[-q | --quiet] [-v | --invert]
PATTERN [STRING ...]
string pad [-r | --right] [(-c | --char) CHAR] [(-w | --width) INTEGER]
[STRING ...]
string repeat [(-n | --count) COUNT] [(-m | --max) MAX] [-N | --no-newline]
[-q | --quiet] [STRING ...]
string repeat [-N | --no-newline] [-q | --quiet] COUNT [STRING ...]
string replace [-a | --all] [-f | --filter] [-i | --ignore-case]
[-r | --regex] [-q | --quiet] PATTERN REPLACE [STRING ...]
string shorten [(-c | --char) CHARS] [(-m | --max) INTEGER]
[-N | --no-newline] [-l | --left] [-q | --quiet] [STRING ...]
string split [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] SEP [STRING ...]
string split0 [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] [STRING ...]
string sub [(-s | --start) START] [(-e | --end) END] [(-l | --length) LENGTH]
[-q | --quiet] [STRING ...]
string trim [-l | --left] [-r | --right] [(-c | --chars) CHARS]
[-q | --quiet] [STRING ...]
string unescape [--style=] [STRING ...]
string upper [-q | --quiet] [STRING ...]
Description
string performs operations on strings.
STRING arguments are taken from the command line unless standard input
is connected to a pipe or a file, in which case they are read from
standard input, one STRING per line. It is an error to supply STRING
arguments on the command line and on standard input.
Arguments beginning with - are normally interpreted as switches; --
causes the following arguments not to be treated as switches even if
they begin with -. Switches and required arguments are recognized only
on the command line.
Most subcommands accept a -q or --quiet switch, which suppresses the
usual output but exits with the documented status. In this case these
commands will quit early, without reading all of the available input.
The following subcommands are available.
"collect" subcommand
string collect [-a | --allow-empty] [-N | --no-trim-newlines] [STRING ...]
string collect collects its input into a single output argument,
without splitting the output when used in a command substitution. This
is useful when trying to collect multiline output from another command
into a variable. Exit status: 0 if any output argument is non-empty, or
1 otherwise.
A command like echo (cmd | string collect) is mostly equivalent to a
quoted command substitution (echo "$(cmd)"). The main difference is
that the former evaluates to zero or one elements whereas the quoted
command substitution always evaluates to one element due to string
interpolation.
If invoked with multiple arguments instead of input, string collect
preserves each argument separately, where the number of output
arguments is equal to the number of arguments given to string collect.
Any trailing newlines on the input are trimmed, just as with "$(cmd)"
substitution. Use --no-trim-newlines to disable this behavior, which
may be useful when running a command such as set contents (cat filename
| string collect -N).
With --allow-empty, string collect always prints one (empty) argument.
This can be used to prevent an argument from disappearing.
Examples
>_ echo "zero $(echo one\ntwo\nthree) four"
zero one
two
three four
>_ echo \"(echo one\ntwo\nthree | string collect)\"
"one
two
three"
>_ echo \"(echo one\ntwo\nthree | string collect -N)\"
"one
two
three
"
>_ echo foo(true | string collect --allow-empty)bar
foobar
"escape" and "unescape" subcommands
string escape [-n | --no-quoted] [--style=] [STRING ...]
string unescape [--style=] [STRING ...]
string escape escapes each STRING in one of several ways.
--style=script (default) alters the string such that it can be passed
back to eval to produce the original argument again. By default, all
special characters are escaped, and quotes are used to simplify the
output when possible. If -n or --no-quoted is given, the simplifying
quoted format is not used. Exit status: 0 if at least one string was
escaped, or 1 otherwise.
--style=var ensures the string can be used as a variable name by hex
encoding any non-alphanumeric characters. The string is first converted
to UTF-8 before being encoded.
--style=url ensures the string can be used as a URL by hex encoding any
character which is not legal in a URL. The string is first converted to
UTF-8 before being encoded.
--style=regex escapes an input string for literal matching within a
regex expression. The string is first converted to UTF-8 before being
encoded.
string unescape performs the inverse of the string escape command. If
the string to be unescaped is not properly formatted it is ignored. For
example, doing string unescape --style=var (string escape --style=var
$str) will return the original string. There is no support for
unescaping --style=regex.
Examples
>_ echo \x07 | string escape
\cg
>_ string escape --style=var 'a1 b2'\u6161
a1_20_b2_E6_85_A1_
"join" and "join0" subcommands
string join [-q | --quiet] SEP [STRING ...]
string join0 [-q | --quiet] [STRING ...]
string join joins its STRING arguments into a single string separated
by SEP, which can be an empty string. Exit status: 0 if at least one
join was performed, or 1 otherwise. If -n or --no-empty is specified,
empty strings are excluded from consideration (e.g. string join -n + a
b "" c would expand to a+b+c not a+b++c).
string join0 joins its STRING arguments into a single string separated
by the zero byte (NUL), and adds a trailing NUL. This is most useful in
conjunction with tools that accept NUL-delimited input, such as sort
-z. Exit status: 0 if at least one join was performed, or 1 otherwise.
Because Unix uses NUL as the string terminator, passing the output of
string join0 as an argument to a command (via a command substitution)
won't actually work. Fish will pass the correct bytes along, but the
command won't be able to tell where the argument ends. This is a
limitation of Unix' argument passing.
Examples
>_ seq 3 | string join ...
1...2...3
# Give a list of NUL-separated filenames to du (this is a GNU extension)
>_ string join0 file1 file2 file\nwith\nmultiple\nlines | du --files0-from=-
# Just put the strings together without a separator
>_ string join '' a b c
abc
"length" subcommand
string length [-q | --quiet] [-V | --visible] [STRING ...]
string length reports the length of each string argument in characters.
Exit status: 0 if at least one non-empty STRING was given, or 1
otherwise.
With -V or --visible, it uses the visible width of the arguments. That
means it will discount escape sequences fish knows about, account for
$fish_emoji_width and $fish_ambiguous_width. It will also count each
line (separated by \n) on its own, and with a carriage return (\r)
count only the widest stretch on a line. The intent is to measure the
number of columns the STRING would occupy in the current terminal.
Examples
>_ string length 'hello, world'
12
>_ set str foo
>_ string length -q $str; echo $status
0
# Equivalent to test -n "$str"
>_ string length --visible (set_color red)foobar
# the set_color is discounted, so this is the width of "foobar"
6
>_ string length --visible >>>>
# depending on $fish_emoji_width, this is either 4 or 8
# in new terminals it should be
8
>_ string length --visible abcdef\r123
# this displays as "123def", so the width is 6
6
>_ string length --visible a\nbc
# counts "a" and "bc" as separate lines, so it prints width for each
1
2
"lower" subcommand
string lower [-q | --quiet] [STRING ...]
string lower converts each string argument to lowercase. Exit status: 0
if at least one string was converted to lowercase, else 1. This means
that in conjunction with the -q flag you can readily test whether a
string is already lowercase.
"match" subcommand
string match [-a | --all] [-e | --entire] [-i | --ignore-case]
[-g | --groups-only] [-r | --regex] [-n | --index]
[-q | --quiet] [-v | --invert] [(-m | --max-matches) MAX]
PATTERN [STRING ...]
string match tests each STRING against PATTERN and prints matching
substrings. Only the first match for each STRING is reported unless -a
or --all is given, in which case all matches are reported.
If you specify the -e or --entire then each matching string is printed
including any prefix or suffix not matched by the pattern (equivalent
to grep without the -o flag). You can, obviously, achieve the same
result by prepending and appending * or .* depending on whether or not
you have specified the --regex flag. The --entire flag is simply a way
to avoid having to complicate the pattern in that fashion and make the
intent of the string match clearer. Without --entire and --regex, a
PATTERN will need to match the entire STRING before it will be
reported.
Matching can be made case-insensitive with --ignore-case or -i.
If --groups-only or -g is given, only the capturing groups will be
reported - meaning the full match will be skipped. This is incompatible
with --entire and --invert, and requires --regex. It is useful as a
simple cutting tool instead of string replace, so you can simply choose
"this part" of a string.
If --index or -n is given, each match is reported as a 1-based start
position and a length. By default, PATTERN is interpreted as a glob
pattern matched against each entire STRING argument. A glob pattern is
only considered a valid match if it matches the entire STRING.
If --regex or -r is given, PATTERN is interpreted as a Perl-compatible
regular expression, which does not have to match the entire STRING. For
a regular expression containing capturing groups, multiple items will
be reported for each match, one for the entire match and one for each
capturing group. With this, only the matching part of the STRING will
be reported, unless --entire is given.
When matching via regular expressions, string match automatically sets
variables for all named capturing groups ((?expression)). It will
create a variable with the name of the group, in the default scope, for
each named capturing group, and set it to the value of the capturing
group in the first matched argument. If a named capture group matched
an empty string, the variable will be set to the empty string (like set
var ""). If it did not match, the variable will be set to nothing (like
set var). When --regex is used with --all, this behavior changes. Each
named variable will contain a list of matches, with the first match
contained in the first element, the second match in the second, and so
on. If the group was empty or did not match, the corresponding element
will be an empty string.
If --invert or -v is used the selected lines will be only those which
do not match the given glob pattern or regular expression.
If --max-matches MAX or -m MAX is used, string will stop checking for
matches after MAX lines of input have matched. This can be used as an
"early exit" optimization when processing long inputs but expecting a
limited and fixed number of outputs that might be found considerably
before the input stream has been exhausted. If combined with --invert
or -v, considers only inverted matches.
Exit status: 0 if at least one match was found, or 1 otherwise.
Match Glob Examples
>_ string match '?' a
a
>_ string match 'a*b' axxb
axxb
>_ string match -i 'a??B' Axxb
Axxb
>_ string match -- '-*' -h foo --version bar
# To match things that look like options, we need a `--`
# to tell string its options end there.
-h
--version
>_ echo 'ok?' | string match '*\?'
ok?
# Note that only the second STRING will match here.
>_ string match 'foo' 'foo1' 'foo' 'foo2'
foo
>_ string match -e 'foo' 'foo1' 'foo' 'foo2'
foo1
foo
foo2
>_ string match 'foo?' 'foo1' 'foo' 'foo2'
foo1
foo2
Match Regex Examples
>_ string match -r 'cat|dog|fish' 'nice dog'
dog
>_ string match -r -v "c.*[12]" {cat,dog}(seq 1 4)
dog1
dog2
cat3
dog3
cat4
dog4
>_ string match -r -- '-.*' -h foo --version bar
# To match things that look like options, we need a `--`
# to tell string its options end there.
-h
--version
>_ string match -r '(\d\d?):(\d\d):(\d\d)' 2:34:56
2:34:56
2
34
56
>_ string match -r '^(\w{2,4})\1$' papa mud murmur
papa
pa
murmur
mur
>_ string match -r -a -n at ratatat
2 2
4 2
6 2
>_ string match -r -i '0x[0-9a-f]{1,8}' 'int magic = 0xBadC0de;'
0xBadC0de
>_ echo $version
3.1.2-1575-ga2ff32d90
>_ string match -rq '(?\d+).(?\d+).(?\d+)' -- $version
>_ echo "You are using fish $major!"
You are using fish 3!
>_ string match -raq ' *(?[^.!?]+)(?[.!?])?' "hello, friend. goodbye"
>_ printf "%s\n" -- $sentence
hello, friend
goodbye
>_ printf "%s\n" -- $punctuation
.
>_ string match -rq '(?hello)' 'hi'
>_ count $word
0
"pad" subcommand
string pad [-r | --right] [(-c | --char) CHAR] [(-w | --width) INTEGER]
[STRING ...]
string pad extends each STRING to the given visible width by adding
CHAR to the left. That means the width of all visible characters added
together, excluding escape sequences and accounting for
fish_emoji_width and fish_ambiguous_width. It is the amount of columns
in a terminal the STRING occupies.
The escape sequences reflect what fish knows about, and how it computes
its output. Your terminal might support more escapes, or not support
escape sequences that fish knows about.
If -r or --right is given, add the padding after a string.
If -c or --char is given, pad with CHAR instead of whitespace.
The output is padded to the maximum width of all input strings. If -w
or --width is given, use at least that.
Examples
>_ string pad -w 10 abc abcdef
abc
abcdef
>_ string pad --right --char=> "fish are pretty" "rich. "
fish are pretty
rich. >>>>
>_ string pad -w$COLUMNS (date)
# Prints the current time on the right edge of the screen.
See also
o The printf command can do simple padding, for example printf %10s\n
works like string pad -w10.
o string length with the --visible option can be used to show what fish
thinks the width is.
"shorten" subcommand
string shorten [(-c | --char) CHARS] [(-m | --max) INTEGER]
[-N | --no-newline] [-l | --left] [-q | --quiet] [STRING ...]
string shorten truncates each STRING to the given visible width and
adds an ellipsis to indicate it. "Visible width" means the width of all
visible characters added together, excluding escape sequences and
accounting for fish_emoji_width and fish_ambiguous_width. It is the
amount of columns in a terminal the STRING occupies.
The escape sequences reflect what fish knows about, and how it computes
its output. Your terminal might support more escapes, or not support
escape sequences that fish knows about.
If -m or --max is given, truncate at the given width. Otherwise, the
lowest non-zero width of all input strings is used. A max of 0 means no
shortening takes place, all STRINGs are printed as-is.
If -N or --no-newline is given, only the first line (or last line with
--left) of each STRING is used, and an ellipsis is added if it was
multiline. This only works for STRINGs being given as arguments,
multiple lines given on stdin will be interpreted as separate STRINGs
instead.
If -c or --char is given, add CHAR instead of an ellipsis. This can
also be empty or more than one character.
If -l or --left is given, remove text from the left on instead, so this
prints the longest suffix of the string that fits. With --no-newline,
this will take from the last line instead of the first.
If -q or --quiet is given, string shorten only runs for the return
value - if anything would be shortened, it returns 0, else 1.
The default ellipsis is >. If fish thinks your system is incapable
because of your locale, it will use ... instead.
The return value is 0 if any shortening occurred, 1 otherwise.
Examples
>_ string shorten foo foobar
# No width was given, we infer, and "foo" is the shortest.
foo
fo>
>_ string shorten --char="..." foo foobar
# The target width is 3 because of "foo",
# and our ellipsis is 3 too, so we can't really show anything.
# This is the default ellipsis if your locale doesn't allow ">".
foo
...
>_ string shorten --char="" --max 4 abcdef 123456
# Leaving the char empty makes us not add an ellipsis
# So this truncates at 4 columns:
abcd
1234
>_ touch "a multiline"\n"file"
>_ for file in *; string shorten -N -- $file; end
# Shorten the multiline file so we only show one line per file:
a multiline>
>_ ss -p | string shorten -m$COLUMNS -c ""
# `ss` from Linux' iproute2 shows socket information, but prints extremely long lines.
# This shortens input so it fits on the screen without overflowing lines.
>_ git branch | string match -rg '^\* (.*)' | string shorten -m20
# Take the current git branch and shorten it at 20 columns.
# Here the branch is "builtin-path-with-expand"
builtin-path-with-e>
>_ git branch | string match -rg '^\* (.*)' | string shorten -m20 --left
# Taking 20 columns from the right instead:
>in-path-with-expand
See also
o string's pad subcommand does the inverse of this command, adding
padding to a specific width instead.
o The printf command can do simple padding, for example printf %10s\n
works like string pad -w10.
o string length with the --visible option can be used to show what fish
thinks the width is.
"repeat" subcommand
string repeat [(-n | --count) COUNT] [(-m | --max) MAX] [-N | --no-newline]
[-q | --quiet] [STRING ...]
string repeat [-N | --no-newline] [-q | --quiet] COUNT [STRING ...]
string repeat repeats the STRING -n or --count times. The -m or --max
option will limit the number of outputted characters (excluding the
newline). This option can be used by itself or in conjunction with
--count. If both --count and --max are present, max char will be
outputted unless the final repeated string size is less than max, in
that case, the string will repeat until count has been reached. Both
--count and --max will accept a number greater than or equal to zero,
in the case of zero, nothing will be outputted. The first argument is
interpreted as COUNT if --count or --max are not explicitly specified.
If -N or --no-newline is given, the output won't contain a newline
character at the end. Exit status: 0 if yielded string is not empty, 1
otherwise.
Examples
Repeat Examples
>_ string repeat -n 2 'foo '
foo foo
>_ echo foo | string repeat -n 2
foofoo
>_ string repeat -n 2 -m 5 'foo'
foofo
>_ string repeat -m 5 'foo'
foofo
>_ string repeat 2 'foo'
foofoo
>_ string repeat 2 -n 3
222
"replace" subcommand
string replace [-a | --all] [-f | --filter] [-i | --ignore-case]
[-r | --regex] [(-m | --max-matches) MAX] [-q | --quiet]
PATTERN REPLACEMENT [STRING ...]
string replace is similar to string match but replaces non-overlapping
matching substrings with a replacement string and prints the result. By
default, PATTERN is treated as a literal substring to be matched.
If -r or --regex is given, PATTERN is interpreted as a Perl-compatible
regular expression, and REPLACEMENT can contain C-style escape
sequences like t as well as references to capturing groups by number or
name as $n or ${n}.
If you specify the -f or --filter flag then each input string is
printed only if a replacement was done. This is useful where you would
otherwise use this idiom: a_cmd | string match pattern | string replace
pattern new_pattern. You can instead just write a_cmd | string replace
--filter pattern new_pattern.
If --max-matches MAX or -m MAX is used, string replace will stop all
processing after MAX lines of input have matched the specified pattern.
In the event of --filter or -f, this means the output will be MAX lines
in length. This can be used as an "early exit" optimization when
processing long inputs but expecting a limited and fixed number of
outputs that might be found considerably before the input stream has
been exhausted.
Exit status: 0 if at least one replacement was performed, or 1
otherwise.
Replace Literal Examples
>_ string replace is was 'blue is my favorite'
blue was my favorite
>_ string replace 3rd last 1st 2nd 3rd
1st
2nd
last
>_ string replace -a ' ' _ 'spaces to underscores'
spaces_to_underscores
Replace Regex Examples
>_ string replace -r -a '[^\d.]+' ' ' '0 one two 3.14 four 5x'
0 3.14 5
>_ string replace -r '(\w+)\s+(\w+)' '$2 $1 $$' 'left right'
right left $
>_ string replace -r '\s*newline\s*' '\n' 'put a newline here'
put a
here
"split" and "split0" subcommands
string split [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] SEP [STRING ...]
string split0 [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] [STRING ...]
string split splits each STRING on the separator SEP, which can be an
empty string. If -m or --max is specified, at most MAX splits are done
on each STRING. If -r or --right is given, splitting is performed
right-to-left. This is useful in combination with -m or --max. With -n
or --no-empty, empty results are excluded from consideration (e.g.
hello\n\nworld would expand to two strings and not three). Exit status:
0 if at least one split was performed, or 1 otherwise.
Use -f or --fields to print out specific fields. FIELDS is a
comma-separated string of field numbers and/or spans. Each field is
one-indexed, and will be printed on separate lines. If a given field
does not exist, then the command exits with status 1 and does not print
anything, unless --allow-empty is used.
See also the --delimiter option of the read command.
string split0 splits each STRING on the zero byte (NUL). Options are
the same as string split except that no separator is given.
split0 has the important property that its output is not further split
when used in a command substitution, allowing for the command
substitution to produce elements containing newlines. This is most
useful when used with Unix tools that produce zero bytes, such as find
-print0 or sort -z. See split0 examples below.
Examples
>_ string split . example.com
example
com
>_ string split -r -m1 / /usr/local/bin/fish
/usr/local/bin
fish
>_ string split '' abc
a
b
c
>_ string split --allow-empty -f1,3-4,5 '' abcd
a
c
d
NUL Delimited Examples
>_ # Count files in a directory, without being confused by newlines.
>_ count (find . -print0 | string split0)
42
>_ # Sort a list of elements which may contain newlines
>_ set foo beta alpha\ngamma
>_ set foo (string join0 $foo | sort -z | string split0)
>_ string escape $foo[1]
alpha\ngamma
"sub" subcommand
string sub [(-s | --start) START] [(-e | --end) END] [(-l | --length) LENGTH]
[-q | --quiet] [STRING ...]
string sub prints a substring of each string argument. The start/end of
the substring can be specified with -s/-e or --start/--end followed by
a 1-based index value. Positive index values are relative to the start
of the string and negative index values are relative to the end of the
string. The default start value is 1. The length of the substring can
be specified with -l or --length. If the length or end is not
specified, the substring continues to the end of each STRING. Exit
status: 0 if at least one substring operation was performed, 1
otherwise. --length is mutually exclusive with --end.
Examples
>_ string sub --length 2 abcde
ab
>_ string sub -s 2 -l 2 abcde
bc
>_ string sub --start=-2 abcde
de
>_ string sub --end=3 abcde
abc
>_ string sub -e -1 abcde
abcd
>_ string sub -s 2 -e -1 abcde
bcd
>_ string sub -s -3 -e -2 abcde
c
"trim" subcommand
string trim [-l | --left] [-r | --right] [(-c | --chars) CHARS]
[-q | --quiet] [STRING ...]
string trim removes leading and trailing whitespace from each STRING.
If -l or --left is given, only leading whitespace is removed. If -r or
--right is given, only trailing whitespace is trimmed.
The -c or --chars switch causes the set of characters in CHARS to be
removed instead of whitespace. This is a set of characters, not a
string - if you pass -c foo, it will remove any "f" or "o", not just
"foo" as a whole.
Exit status: 0 if at least one character was trimmed, or 1 otherwise.
Examples
>_ string trim ' abc '
abc
>_ string trim --right --chars=yz xyzzy zany
x
zan
"upper" subcommand
string upper [-q | --quiet] [STRING ...]
string upper converts each string argument to uppercase. Exit status: 0
if at least one string was converted to uppercase, else 1. This means
that in conjunction with the -q flag you can readily test whether a
string is already uppercase.
Regular Expressions
Both the match and replace subcommand support regular expressions when
used with the -r or --regex option. The dialect is that of PCRE2.
In general, special characters are special by default, so a+ matches
one or more "a"s, while a\+ matches an "a" and then a "+". (a+) matches
one or more "a"s in a capturing group ((?:XXXX) denotes a non-capturing
group). For the replacement parameter of replace, $n refers to the n-th
group of the match. In the match parameter, \n (e.g. \1) refers back to
groups.
Some features include repetitions:
o * refers to 0 or more repetitions of the previous expression
o + 1 or more
o ? 0 or 1.
o {n} to exactly n (where n is a number)
o {n,m} at least n, no more than m.
o {n,} n or more
Character classes, some of the more important:
o . any character except newline
o \d a decimal digit and \D, not a decimal digit
o \s whitespace and \S, not whitespace
o \w a "word" character and \W, a "non-word" character
o [...] (where "..." is some characters) is a character set
o [^...] is the inverse of the given character set
o [x-y] is the range of characters from x-y
o [[:xxx:]] is a named character set
o [[:^xxx:]] is the inverse of a named character set
o [[:alnum:]] : "alphanumeric"
o [[:alpha:]] : "alphabetic"
o [[:ascii:]] : "0-127"
o [[:blank:]] : "space or tab"
o [[:cntrl:]] : "control character"
o [[:digit:]] : "decimal digit"
o [[:graph:]] : "printing, excluding space"
o [[:lower:]] : "lower case letter"
o [[:print:]] : "printing, including space"
o [[:punct:]] : "printing, excluding alphanumeric"
o [[:space:]] : "white space"
o [[:upper:]] : "upper case letter"
o [[:word:]] : "same as w"
o [[:xdigit:]] : "hexadecimal digit"
Groups:
o (...) is a capturing group
o (?:...) is a non-capturing group
o \n is a backreference (where n is the number of the group, starting
with 1)
o $n is a reference from the replacement expression to a group in the
match expression.
And some other things:
o \b denotes a word boundary, \B is not a word boundary.
o ^ is the start of the string or line, $ the end.
o | is "alternation", i.e. the "or".
Comparison to other tools
Most operations string supports can also be done by external tools.
Some of these include grep, sed and cut.
If you are familiar with these, it is useful to know how string differs
from them.
In contrast to these classics, string reads input either from stdin or
as arguments. string also does not deal with files, so it requires
redirections to be used with them.
In contrast to grep, string's match defaults to glob-mode, while
replace defaults to literal matching. If set to regex-mode, they use
PCRE regular expressions, which is comparable to grep's -P option.
match defaults to printing just the match, which is like grep with -o
(use --entire to enable grep-like behavior).
Like sed's s/old/new/ command, string replace still prints strings that
don't match. sed's -n in combination with a /p modifier or command is
like string replace -f.
string split somedelimiter is a replacement for tr somedelimiter \n.
string-collect - join strings into one
Synopsis
string collect [-a | --allow-empty] [-N | --no-trim-newlines] [STRING ...]
Description
string collect collects its input into a single output argument,
without splitting the output when used in a command substitution. This
is useful when trying to collect multiline output from another command
into a variable. Exit status: 0 if any output argument is non-empty, or
1 otherwise.
A command like echo (cmd | string collect) is mostly equivalent to a
quoted command substitution (echo "$(cmd)"). The main difference is
that the former evaluates to zero or one elements whereas the quoted
command substitution always evaluates to one element due to string
interpolation.
If invoked with multiple arguments instead of input, string collect
preserves each argument separately, where the number of output
arguments is equal to the number of arguments given to string collect.
Any trailing newlines on the input are trimmed, just as with "$(cmd)"
substitution. Use --no-trim-newlines to disable this behavior, which
may be useful when running a command such as set contents (cat filename
| string collect -N).
With --allow-empty, string collect always prints one (empty) argument.
This can be used to prevent an argument from disappearing.
Examples
>_ echo "zero $(echo one\ntwo\nthree) four"
zero one
two
three four
>_ echo \"(echo one\ntwo\nthree | string collect)\"
"one
two
three"
>_ echo \"(echo one\ntwo\nthree | string collect -N)\"
"one
two
three
"
>_ echo foo(true | string collect --allow-empty)bar
foobar
string-escape - escape special characters
Synopsis
string escape [-n | --no-quoted] [--style=] [STRING ...]
string unescape [--style=] [STRING ...]
Description
string escape escapes each STRING in one of several ways.
--style=script (default) alters the string such that it can be passed
back to eval to produce the original argument again. By default, all
special characters are escaped, and quotes are used to simplify the
output when possible. If -n or --no-quoted is given, the simplifying
quoted format is not used. Exit status: 0 if at least one string was
escaped, or 1 otherwise.
--style=var ensures the string can be used as a variable name by hex
encoding any non-alphanumeric characters. The string is first converted
to UTF-8 before being encoded.
--style=url ensures the string can be used as a URL by hex encoding any
character which is not legal in a URL. The string is first converted to
UTF-8 before being encoded.
--style=regex escapes an input string for literal matching within a
regex expression. The string is first converted to UTF-8 before being
encoded.
string unescape performs the inverse of the string escape command. If
the string to be unescaped is not properly formatted it is ignored. For
example, doing string unescape --style=var (string escape --style=var
$str) will return the original string. There is no support for
unescaping --style=regex.
Examples
>_ echo \x07 | string escape
\cg
>_ string escape --style=var 'a1 b2'\u6161
a1_20_b2_E6_85_A1_
string-join - join strings with delimiter
Synopsis
string join [-q | --quiet] SEP [STRING ...]
string join0 [-q | --quiet] [STRING ...]
Description
string join joins its STRING arguments into a single string separated
by SEP, which can be an empty string. Exit status: 0 if at least one
join was performed, or 1 otherwise. If -n or --no-empty is specified,
empty strings are excluded from consideration (e.g. string join -n + a
b "" c would expand to a+b+c not a+b++c).
string join0 joins its STRING arguments into a single string separated
by the zero byte (NUL), and adds a trailing NUL. This is most useful in
conjunction with tools that accept NUL-delimited input, such as sort
-z. Exit status: 0 if at least one join was performed, or 1 otherwise.
Because Unix uses NUL as the string terminator, passing the output of
string join0 as an argument to a command (via a command substitution)
won't actually work. Fish will pass the correct bytes along, but the
command won't be able to tell where the argument ends. This is a
limitation of Unix' argument passing.
Examples
>_ seq 3 | string join ...
1...2...3
# Give a list of NUL-separated filenames to du (this is a GNU extension)
>_ string join0 file1 file2 file\nwith\nmultiple\nlines | du --files0-from=-
# Just put the strings together without a separator
>_ string join '' a b c
abc
string-join0 - join strings with zero bytes
Synopsis
string join [-q | --quiet] SEP [STRING ...]
string join0 [-q | --quiet] [STRING ...]
Description
string join joins its STRING arguments into a single string separated
by SEP, which can be an empty string. Exit status: 0 if at least one
join was performed, or 1 otherwise. If -n or --no-empty is specified,
empty strings are excluded from consideration (e.g. string join -n + a
b "" c would expand to a+b+c not a+b++c).
string join0 joins its STRING arguments into a single string separated
by the zero byte (NUL), and adds a trailing NUL. This is most useful in
conjunction with tools that accept NUL-delimited input, such as sort
-z. Exit status: 0 if at least one join was performed, or 1 otherwise.
Because Unix uses NUL as the string terminator, passing the output of
string join0 as an argument to a command (via a command substitution)
won't actually work. Fish will pass the correct bytes along, but the
command won't be able to tell where the argument ends. This is a
limitation of Unix' argument passing.
Examples
>_ seq 3 | string join ...
1...2...3
# Give a list of NUL-separated filenames to du (this is a GNU extension)
>_ string join0 file1 file2 file\nwith\nmultiple\nlines | du --files0-from=-
# Just put the strings together without a separator
>_ string join '' a b c
abc
string-length - print string lengths
Synopsis
string length [-q | --quiet] [-V | --visible] [STRING ...]
Description
string length reports the length of each string argument in characters.
Exit status: 0 if at least one non-empty STRING was given, or 1
otherwise.
With -V or --visible, it uses the visible width of the arguments. That
means it will discount escape sequences fish knows about, account for
$fish_emoji_width and $fish_ambiguous_width. It will also count each
line (separated by \n) on its own, and with a carriage return (\r)
count only the widest stretch on a line. The intent is to measure the
number of columns the STRING would occupy in the current terminal.
Examples
>_ string length 'hello, world'
12
>_ set str foo
>_ string length -q $str; echo $status
0
# Equivalent to test -n "$str"
>_ string length --visible (set_color red)foobar
# the set_color is discounted, so this is the width of "foobar"
6
>_ string length --visible >>>>
# depending on $fish_emoji_width, this is either 4 or 8
# in new terminals it should be
8
>_ string length --visible abcdef\r123
# this displays as "123def", so the width is 6
6
>_ string length --visible a\nbc
# counts "a" and "bc" as separate lines, so it prints width for each
1
2
string-lower - convert strings to lowercase
Synopsis
string lower [-q | --quiet] [STRING ...]
Description
string lower converts each string argument to lowercase. Exit status: 0
if at least one string was converted to lowercase, else 1. This means
that in conjunction with the -q flag you can readily test whether a
string is already lowercase.
string-match - match substrings
Synopsis
string match [-a | --all] [-e | --entire] [-i | --ignore-case]
[-g | --groups-only] [-r | --regex] [-n | --index]
[-q | --quiet] [-v | --invert] [(-m | --max-matches) MAX]
PATTERN [STRING ...]
Description
string match tests each STRING against PATTERN and prints matching
substrings. Only the first match for each STRING is reported unless -a
or --all is given, in which case all matches are reported.
If you specify the -e or --entire then each matching string is printed
including any prefix or suffix not matched by the pattern (equivalent
to grep without the -o flag). You can, obviously, achieve the same
result by prepending and appending * or .* depending on whether or not
you have specified the --regex flag. The --entire flag is simply a way
to avoid having to complicate the pattern in that fashion and make the
intent of the string match clearer. Without --entire and --regex, a
PATTERN will need to match the entire STRING before it will be
reported.
Matching can be made case-insensitive with --ignore-case or -i.
If --groups-only or -g is given, only the capturing groups will be
reported - meaning the full match will be skipped. This is incompatible
with --entire and --invert, and requires --regex. It is useful as a
simple cutting tool instead of string replace, so you can simply choose
"this part" of a string.
If --index or -n is given, each match is reported as a 1-based start
position and a length. By default, PATTERN is interpreted as a glob
pattern matched against each entire STRING argument. A glob pattern is
only considered a valid match if it matches the entire STRING.
If --regex or -r is given, PATTERN is interpreted as a Perl-compatible
regular expression, which does not have to match the entire STRING. For
a regular expression containing capturing groups, multiple items will
be reported for each match, one for the entire match and one for each
capturing group. With this, only the matching part of the STRING will
be reported, unless --entire is given.
When matching via regular expressions, string match automatically sets
variables for all named capturing groups ((?expression)). It will
create a variable with the name of the group, in the default scope, for
each named capturing group, and set it to the value of the capturing
group in the first matched argument. If a named capture group matched
an empty string, the variable will be set to the empty string (like set
var ""). If it did not match, the variable will be set to nothing (like
set var). When --regex is used with --all, this behavior changes. Each
named variable will contain a list of matches, with the first match
contained in the first element, the second match in the second, and so
on. If the group was empty or did not match, the corresponding element
will be an empty string.
If --invert or -v is used the selected lines will be only those which
do not match the given glob pattern or regular expression.
If --max-matches MAX or -m MAX is used, string will stop checking for
matches after MAX lines of input have matched. This can be used as an
"early exit" optimization when processing long inputs but expecting a
limited and fixed number of outputs that might be found considerably
before the input stream has been exhausted. If combined with --invert
or -v, considers only inverted matches.
Exit status: 0 if at least one match was found, or 1 otherwise.
Examples
Match Glob Examples
>_ string match '?' a
a
>_ string match 'a*b' axxb
axxb
>_ string match -i 'a??B' Axxb
Axxb
>_ string match -- '-*' -h foo --version bar
# To match things that look like options, we need a `--`
# to tell string its options end there.
-h
--version
>_ echo 'ok?' | string match '*\?'
ok?
# Note that only the second STRING will match here.
>_ string match 'foo' 'foo1' 'foo' 'foo2'
foo
>_ string match -e 'foo' 'foo1' 'foo' 'foo2'
foo1
foo
foo2
>_ string match 'foo?' 'foo1' 'foo' 'foo2'
foo1
foo2
Match Regex Examples
>_ string match -r 'cat|dog|fish' 'nice dog'
dog
>_ string match -r -v "c.*[12]" {cat,dog}(seq 1 4)
dog1
dog2
cat3
dog3
cat4
dog4
>_ string match -r -- '-.*' -h foo --version bar
# To match things that look like options, we need a `--`
# to tell string its options end there.
-h
--version
>_ string match -r '(\d\d?):(\d\d):(\d\d)' 2:34:56
2:34:56
2
34
56
>_ string match -r '^(\w{2,4})\1$' papa mud murmur
papa
pa
murmur
mur
>_ string match -r -a -n at ratatat
2 2
4 2
6 2
>_ string match -r -i '0x[0-9a-f]{1,8}' 'int magic = 0xBadC0de;'
0xBadC0de
>_ echo $version
3.1.2-1575-ga2ff32d90
>_ string match -rq '(?\d+).(?\d+).(?\d+)' -- $version
>_ echo "You are using fish $major!"
You are using fish 3!
>_ string match -raq ' *(?[^.!?]+)(?[.!?])?' "hello, friend. goodbye"
>_ printf "%s\n" -- $sentence
hello, friend
goodbye
>_ printf "%s\n" -- $punctuation
.
>_ string match -rq '(?hello)' 'hi'
>_ count $word
0
string-pad - pad strings to a fixed width
Synopsis
string pad [-r | --right] [(-c | --char) CHAR] [(-w | --width) INTEGER]
[STRING ...]
Description
string pad extends each STRING to the given visible width by adding
CHAR to the left. That means the width of all visible characters added
together, excluding escape sequences and accounting for
fish_emoji_width and fish_ambiguous_width. It is the amount of columns
in a terminal the STRING occupies.
The escape sequences reflect what fish knows about, and how it computes
its output. Your terminal might support more escapes, or not support
escape sequences that fish knows about.
If -r or --right is given, add the padding after a string.
If -c or --char is given, pad with CHAR instead of whitespace.
The output is padded to the maximum width of all input strings. If -w
or --width is given, use at least that.
Examples
>_ string pad -w 10 abc abcdef
abc
abcdef
>_ string pad --right --char=> "fish are pretty" "rich. "
fish are pretty
rich. >>>>
>_ string pad -w$COLUMNS (date)
# Prints the current time on the right edge of the screen.
See Also
o The printf command can do simple padding, for example printf %10s\n
works like string pad -w10.
o string length with the --visible option can be used to show what fish
thinks the width is.
string-repeat - multiply a string
Synopsis
string repeat [(-n | --count) COUNT] [(-m | --max) MAX] [-N | --no-newline]
[-q | --quiet] [STRING ...]
string repeat [-N | --no-newline] [-q | --quiet] COUNT [STRING ...]
Description
string repeat repeats the STRING -n or --count times. The -m or --max
option will limit the number of outputted characters (excluding the
newline). This option can be used by itself or in conjunction with
--count. If both --count and --max are present, max char will be
outputted unless the final repeated string size is less than max, in
that case, the string will repeat until count has been reached. Both
--count and --max will accept a number greater than or equal to zero,
in the case of zero, nothing will be outputted. The first argument is
interpreted as COUNT if --count or --max are not explicitly specified.
If -N or --no-newline is given, the output won't contain a newline
character at the end. Exit status: 0 if yielded string is not empty, 1
otherwise.
Examples
Repeat Examples
>_ string repeat -n 2 'foo '
foo foo
>_ echo foo | string repeat -n 2
foofoo
>_ string repeat -n 2 -m 5 'foo'
foofo
>_ string repeat -m 5 'foo'
foofo
>_ string repeat 2 'foo'
foofoo
>_ string repeat 2 -n 3
222
string-replace - replace substrings
Synopsis
string replace [-a | --all] [-f | --filter] [-i | --ignore-case]
[-r | --regex] [(-m | --max-matches) MAX] [-q | --quiet]
PATTERN REPLACEMENT [STRING ...]
Description
string replace is similar to string match but replaces non-overlapping
matching substrings with a replacement string and prints the result. By
default, PATTERN is treated as a literal substring to be matched.
If -r or --regex is given, PATTERN is interpreted as a Perl-compatible
regular expression, and REPLACEMENT can contain C-style escape
sequences like t as well as references to capturing groups by number or
name as $n or ${n}.
If you specify the -f or --filter flag then each input string is
printed only if a replacement was done. This is useful where you would
otherwise use this idiom: a_cmd | string match pattern | string replace
pattern new_pattern. You can instead just write a_cmd | string replace
--filter pattern new_pattern.
If --max-matches MAX or -m MAX is used, string replace will stop all
processing after MAX lines of input have matched the specified pattern.
In the event of --filter or -f, this means the output will be MAX lines
in length. This can be used as an "early exit" optimization when
processing long inputs but expecting a limited and fixed number of
outputs that might be found considerably before the input stream has
been exhausted.
Exit status: 0 if at least one replacement was performed, or 1
otherwise.
Examples
Replace Literal Examples
>_ string replace is was 'blue is my favorite'
blue was my favorite
>_ string replace 3rd last 1st 2nd 3rd
1st
2nd
last
>_ string replace -a ' ' _ 'spaces to underscores'
spaces_to_underscores
Replace Regex Examples
>_ string replace -r -a '[^\d.]+' ' ' '0 one two 3.14 four 5x'
0 3.14 5
>_ string replace -r '(\w+)\s+(\w+)' '$2 $1 $$' 'left right'
right left $
>_ string replace -r '\s*newline\s*' '\n' 'put a newline here'
put a
here
string-shorten - shorten strings to a width, with an ellipsis
Synopsis
string shorten [(-c | --char) CHARS] [(-m | --max) INTEGER]
[-N | --no-newline] [-l | --left] [-q | --quiet] [STRING ...]
Description
string shorten truncates each STRING to the given visible width and
adds an ellipsis to indicate it. "Visible width" means the width of all
visible characters added together, excluding escape sequences and
accounting for fish_emoji_width and fish_ambiguous_width. It is the
amount of columns in a terminal the STRING occupies.
The escape sequences reflect what fish knows about, and how it computes
its output. Your terminal might support more escapes, or not support
escape sequences that fish knows about.
If -m or --max is given, truncate at the given width. Otherwise, the
lowest non-zero width of all input strings is used. A max of 0 means no
shortening takes place, all STRINGs are printed as-is.
If -N or --no-newline is given, only the first line (or last line with
--left) of each STRING is used, and an ellipsis is added if it was
multiline. This only works for STRINGs being given as arguments,
multiple lines given on stdin will be interpreted as separate STRINGs
instead.
If -c or --char is given, add CHAR instead of an ellipsis. This can
also be empty or more than one character.
If -l or --left is given, remove text from the left on instead, so this
prints the longest suffix of the string that fits. With --no-newline,
this will take from the last line instead of the first.
If -q or --quiet is given, string shorten only runs for the return
value - if anything would be shortened, it returns 0, else 1.
The default ellipsis is >. If fish thinks your system is incapable
because of your locale, it will use ... instead.
The return value is 0 if any shortening occurred, 1 otherwise.
Examples
>_ string shorten foo foobar
# No width was given, we infer, and "foo" is the shortest.
foo
fo>
>_ string shorten --char="..." foo foobar
# The target width is 3 because of "foo",
# and our ellipsis is 3 too, so we can't really show anything.
# This is the default ellipsis if your locale doesn't allow ">".
foo
...
>_ string shorten --char="" --max 4 abcdef 123456
# Leaving the char empty makes us not add an ellipsis
# So this truncates at 4 columns:
abcd
1234
>_ touch "a multiline"\n"file"
>_ for file in *; string shorten -N -- $file; end
# Shorten the multiline file so we only show one line per file:
a multiline>
>_ ss -p | string shorten -m$COLUMNS -c ""
# `ss` from Linux' iproute2 shows socket information, but prints extremely long lines.
# This shortens input so it fits on the screen without overflowing lines.
>_ git branch | string match -rg '^\* (.*)' | string shorten -m20
# Take the current git branch and shorten it at 20 columns.
# Here the branch is "builtin-path-with-expand"
builtin-path-with-e>
>_ git branch | string match -rg '^\* (.*)' | string shorten -m20 --left
# Taking 20 columns from the right instead:
>in-path-with-expand
See Also
o string's pad subcommand does the inverse of this command, adding
padding to a specific width instead.
o The printf command can do simple padding, for example printf %10s\n
works like string pad -w10.
o string length with the --visible option can be used to show what fish
thinks the width is.
string-split - split strings by delimiter
Synopsis
string split [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] SEP [STRING ...]
string split0 [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] [STRING ...]
Description
string split splits each STRING on the separator SEP, which can be an
empty string. If -m or --max is specified, at most MAX splits are done
on each STRING. If -r or --right is given, splitting is performed
right-to-left. This is useful in combination with -m or --max. With -n
or --no-empty, empty results are excluded from consideration (e.g.
hello\n\nworld would expand to two strings and not three). Exit status:
0 if at least one split was performed, or 1 otherwise.
Use -f or --fields to print out specific fields. FIELDS is a
comma-separated string of field numbers and/or spans. Each field is
one-indexed, and will be printed on separate lines. If a given field
does not exist, then the command exits with status 1 and does not print
anything, unless --allow-empty is used.
See also the --delimiter option of the read command.
string split0 splits each STRING on the zero byte (NUL). Options are
the same as string split except that no separator is given.
split0 has the important property that its output is not further split
when used in a command substitution, allowing for the command
substitution to produce elements containing newlines. This is most
useful when used with Unix tools that produce zero bytes, such as find
-print0 or sort -z. See split0 examples below.
Examples
>_ string split . example.com
example
com
>_ string split -r -m1 / /usr/local/bin/fish
/usr/local/bin
fish
>_ string split '' abc
a
b
c
>_ string split --allow-empty -f1,3-4,5 '' abcd
a
c
d
NUL Delimited Examples
>_ # Count files in a directory, without being confused by newlines.
>_ count (find . -print0 | string split0)
42
>_ # Sort a list of elements which may contain newlines
>_ set foo beta alpha\ngamma
>_ set foo (string join0 $foo | sort -z | string split0)
>_ string escape $foo[1]
alpha\ngamma
string-split0 - split on zero bytes
Synopsis
string split [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] SEP [STRING ...]
string split0 [(-f | --fields) FIELDS] [(-m | --max) MAX] [-n | --no-empty]
[-q | --quiet] [-r | --right] [STRING ...]
Description
string split splits each STRING on the separator SEP, which can be an
empty string. If -m or --max is specified, at most MAX splits are done
on each STRING. If -r or --right is given, splitting is performed
right-to-left. This is useful in combination with -m or --max. With -n
or --no-empty, empty results are excluded from consideration (e.g.
hello\n\nworld would expand to two strings and not three). Exit status:
0 if at least one split was performed, or 1 otherwise.
Use -f or --fields to print out specific fields. FIELDS is a
comma-separated string of field numbers and/or spans. Each field is
one-indexed, and will be printed on separate lines. If a given field
does not exist, then the command exits with status 1 and does not print
anything, unless --allow-empty is used.
See also the --delimiter option of the read command.
string split0 splits each STRING on the zero byte (NUL). Options are
the same as string split except that no separator is given.
split0 has the important property that its output is not further split
when used in a command substitution, allowing for the command
substitution to produce elements containing newlines. This is most
useful when used with Unix tools that produce zero bytes, such as find
-print0 or sort -z. See split0 examples below.
Examples
>_ string split . example.com
example
com
>_ string split -r -m1 / /usr/local/bin/fish
/usr/local/bin
fish
>_ string split '' abc
a
b
c
>_ string split --allow-empty -f1,3-4,5 '' abcd
a
c
d
NUL Delimited Examples
>_ # Count files in a directory, without being confused by newlines.
>_ count (find . -print0 | string split0)
42
>_ # Sort a list of elements which may contain newlines
>_ set foo beta alpha\ngamma
>_ set foo (string join0 $foo | sort -z | string split0)
>_ string escape $foo[1]
alpha\ngamma
string-sub - extract substrings
Synopsis
string sub [(-s | --start) START] [(-e | --end) END] [(-l | --length) LENGTH]
[-q | --quiet] [STRING ...]
Description
string sub prints a substring of each string argument. The start/end of
the substring can be specified with -s/-e or --start/--end followed by
a 1-based index value. Positive index values are relative to the start
of the string and negative index values are relative to the end of the
string. The default start value is 1. The length of the substring can
be specified with -l or --length. If the length or end is not
specified, the substring continues to the end of each STRING. Exit
status: 0 if at least one substring operation was performed, 1
otherwise. --length is mutually exclusive with --end.
Examples
>_ string sub --length 2 abcde
ab
>_ string sub -s 2 -l 2 abcde
bc
>_ string sub --start=-2 abcde
de
>_ string sub --end=3 abcde
abc
>_ string sub -e -1 abcde
abcd
>_ string sub -s 2 -e -1 abcde
bcd
>_ string sub -s -3 -e -2 abcde
c
string-trim - remove trailing whitespace
Synopsis
string trim [-l | --left] [-r | --right] [(-c | --chars) CHARS]
[-q | --quiet] [STRING ...]
Description
string trim removes leading and trailing whitespace from each STRING.
If -l or --left is given, only leading whitespace is removed. If -r or
--right is given, only trailing whitespace is trimmed.
The -c or --chars switch causes the set of characters in CHARS to be
removed instead of whitespace. This is a set of characters, not a
string - if you pass -c foo, it will remove any "f" or "o", not just
"foo" as a whole.
Exit status: 0 if at least one character was trimmed, or 1 otherwise.
Examples
>_ string trim ' abc '
abc
>_ string trim --right --chars=yz xyzzy zany
x
zan
string-unescape - expand escape sequences
Synopsis
string escape [-n | --no-quoted] [--style=] [STRING ...]
string unescape [--style=] [STRING ...]
Description
string escape escapes each STRING in one of several ways.
--style=script (default) alters the string such that it can be passed
back to eval to produce the original argument again. By default, all
special characters are escaped, and quotes are used to simplify the
output when possible. If -n or --no-quoted is given, the simplifying
quoted format is not used. Exit status: 0 if at least one string was
escaped, or 1 otherwise.
--style=var ensures the string can be used as a variable name by hex
encoding any non-alphanumeric characters. The string is first converted
to UTF-8 before being encoded.
--style=url ensures the string can be used as a URL by hex encoding any
character which is not legal in a URL. The string is first converted to
UTF-8 before being encoded.
--style=regex escapes an input string for literal matching within a
regex expression. The string is first converted to UTF-8 before being
encoded.
string unescape performs the inverse of the string escape command. If
the string to be unescaped is not properly formatted it is ignored. For
example, doing string unescape --style=var (string escape --style=var
$str) will return the original string. There is no support for
unescaping --style=regex.
Examples
>_ echo \x07 | string escape
\cg
>_ string escape --style=var 'a1 b2'\u6161
a1_20_b2_E6_85_A1_
string-upper - convert strings to uppercase
Synopsis
string upper [-q | --quiet] [STRING ...]
Description
string upper converts each string argument to uppercase. Exit status: 0
if at least one string was converted to uppercase, else 1. This means
that in conjunction with the -q flag you can readily test whether a
string is already uppercase.
suspend - suspend the current shell
Synopsis
suspend [--force]
Description
suspend suspends execution of the current shell by sending it a SIGTSTP
signal, returning to the controlling process. It can be resumed later
by sending it a SIGCONT. In order to prevent suspending a shell that
doesn't have a controlling process, it will not suspend the shell if it
is a login shell. This requirement is bypassed if the --force option is
given or the shell is not interactive.
switch - conditionally execute a block of commands
Synopsis
switch VALUE; [case [GLOB ...]; [COMMANDS ...]; ...] end
Description
switch performs one of several blocks of commands, depending on whether
a specified value equals one of several globbed values. case is used
together with the switch statement in order to determine which block
should be executed.
Each case command is given one or more parameters. The first case
command with a parameter that matches the string specified in the
switch command will be evaluated. case parameters may contain globs.
These need to be escaped or quoted in order to avoid regular glob
expansion using filenames.
Note that fish does not fall through on case statements. Only the first
matching case is executed.
Note that break cannot be used to exit a case/switch block early like
in other languages. It can only be used in loops.
Note that command substitutions in a case statement will be evaluated
even if its body is not taken. All substitutions, including command
substitutions, must be performed before the value can be compared
against the parameter.
Example
If the variable $animal contains the name of an animal, the following
code would attempt to classify it:
switch $animal
case cat
echo evil
case wolf dog human moose dolphin whale
echo mammal
case duck goose albatross
echo bird
case shark trout stingray
echo fish
case '*'
echo I have no idea what a $animal is
end
If the above code was run with $animal set to whale, the output would
be mammal.
test - perform tests on files and text
Synopsis
test [EXPRESSION]
[ [EXPRESSION] ]
Description
NOTE: This page documents the fish builtin test. To see the
documentation on any non-fish versions, use command man test.
test checks the given conditions and sets the exit status to 0 if they
are true, 1 if they are false.
The first form (test) is preferred. For compatibility with other
shells, the second form is available: a matching pair of square
brackets ([ [EXPRESSION] ]).
When using a variable or command substitution as an argument with test
you should almost always enclose it in double-quotes, as variables
expanding to zero or more than one argument will most likely interact
badly with test.
WARNING:
For historical reasons, test supports the one-argument form (test
foo), and this will also be triggered by e.g. test -n $foo if $foo
is unset. We recommend you don't use the one-argument form and quote
all variables or command substitutions used with test.
This confusing misfeature will be removed in future. test -n without
any additional argument will be false, test -z will be true and any
other invocation with exactly one or zero arguments, including test
-d and test "foo" will be an error.
The same goes for [, e.g. [ "foo" ] and [ -d ] will be errors.
This can be turned on already via the test-require-arg feature flag,
and will eventually become the default and then only option.
Operators for files and directories
-b FILE
Returns true if FILE is a block device.
-c FILE
Returns true if FILE is a character device.
-d FILE
Returns true if FILE is a directory.
-e FILE
Returns true if FILE exists.
-f FILE
Returns true if FILE is a regular file.
-g FILE
Returns true if FILE has the set-group-ID bit set.
-G FILE
Returns true if FILE exists and has the same group ID as the
current user.
-k FILE
Returns true if FILE has the sticky bit set. If the OS does not
support the concept it returns false. See
https://en.wikipedia.org/wiki/Sticky_bit.
-L FILE
Returns true if FILE is a symbolic link.
-O FILE
Returns true if FILE exists and is owned by the current user.
-p FILE
Returns true if FILE is a named pipe.
-r FILE
Returns true if FILE is marked as readable.
-s FILE
Returns true if the size of FILE is greater than zero.
-S FILE
Returns true if FILE is a socket.
-t FD Returns true if the file descriptor FD is a terminal (TTY).
-u FILE
Returns true if FILE has the set-user-ID bit set.
-w FILE
Returns true if FILE is marked as writable; note that this does
not check if the filesystem is read-only.
-x FILE
Returns true if FILE is marked as executable.
Operators to compare files and directories
FILE1 -nt FILE2
Returns true if FILE1 is newer than FILE2, or FILE1 exists and
FILE2 does not.
FILE1 -ot FILE2
Returns true if FILE1 is older than FILE2, or FILE2 exists and
FILE1 does not.
FILE1 -ef FILE1
Returns true if FILE1 and FILE2 refer to the same file.
Operators for text strings
STRING1 = STRING2
Returns true if the strings STRING1 and STRING2 are identical.
STRING1 != STRING2
Returns true if the strings STRING1 and STRING2 are not
identical.
-n STRING
Returns true if the length of STRING is non-zero.
-z STRING
Returns true if the length of STRING is zero.
Operators to compare and examine numbers
NUM1 -eq NUM2
Returns true if NUM1 and NUM2 are numerically equal.
NUM1 -ne NUM2
Returns true if NUM1 and NUM2 are not numerically equal.
NUM1 -gt NUM2
Returns true if NUM1 is greater than NUM2.
NUM1 -ge NUM2
Returns true if NUM1 is greater than or equal to NUM2.
NUM1 -lt NUM2
Returns true if NUM1 is less than NUM2.
NUM1 -le NUM2
Returns true if NUM1 is less than or equal to NUM2.
Both integers and floating point numbers are supported.
Operators to combine expressions
COND1 -a COND2
Returns true if both COND1 and COND2 are true.
COND1 -o COND2
Returns true if either COND1 or COND2 are true.
Expressions can be inverted using the ! operator:
! EXPRESSION
Returns true if EXPRESSION is false, and false if EXPRESSION is
true.
Expressions can be grouped using parentheses.
( EXPRESSION )
Returns the value of EXPRESSION.
Note that parentheses will usually require escaping with \ (so they
appear as \( and \)) to avoid being interpreted as a command
substitution.
Examples
If the /tmp directory exists, copy the /etc/motd file to it:
if test -d /tmp
cp /etc/motd /tmp/motd
end
If the variable MANPATH is defined and not empty, print the contents.
(If MANPATH is not defined, then it will expand to zero arguments,
unless quoted.)
if test -n "$MANPATH"
echo $MANPATH
end
Be careful with unquoted variables:
if test -n $MANPATH
# This will also be reached if $MANPATH is unset,
# because in that case we have `test -n`, so it checks if "-n" is non-empty, and it is.
echo $MANPATH
end
This will change in a future release of fish, or already with the
test-require-arg feature flag - if $MANPATH is unset, if test -n
$MANPATH will be false.
Parentheses and the -o and -a operators can be combined to produce more
complicated expressions. In this example, success is printed if there
is a /foo or /bar file as well as a /baz or /bat file.
if test \( -f /foo -o -f /bar \) -a \( -f /baz -o -f /bat \)
echo Success.
end
Numerical comparisons will simply fail if one of the operands is not a
number:
if test 42 -eq "The answer to life, the universe and everything"
echo So long and thanks for all the fish # will not be executed
end
A common comparison is with status:
if test $status -eq 0
echo "Previous command succeeded"
end
The previous test can likewise be inverted:
if test ! $status -eq 0
echo "Previous command failed"
end
which is logically equivalent to the following:
if test $status -ne 0
echo "Previous command failed"
end
Standards
Unlike many things in fish, test implements a subset of the IEEE Std
1003.1-2008 (POSIX.1) standard
.
The following exceptions apply:
o The < and > operators for comparing strings are not implemented.
o With test-require-arg, the zero- and one-argument modes will behave
differently.
In cases such as this, one can use command test to explicitly use
the system's standalone test rather than this builtin test.
See also
Other commands that may be useful as a condition, and are often easier
to use:
o string - manipulate strings, which can do string operations including
wildcard and regular expression matching
o path - manipulate and check paths, which can do file checks and
operations, including filters on multiple paths at once
time - measure how long a command or block takes
Synopsis
time COMMAND
Description
NOTE: This page documents the fish keyword time. To see the
documentation on any non-fish versions, use command man time.
time causes fish to measure how long a command takes and print the
results afterwards. The command can be a simple fish command or a
block. The results can not currently be redirected.
For checking timing after a command has completed, check $CMD_DURATION.
Your system most likely also has a time command. To use that use
something like command time, as in command time sleep 10. Because it's
not inside fish, it won't have access to fish functions and won't be
able to time blocks and such.
How to interpret the output
Time outputs a few different values. Let's look at an example:
> time string repeat -n 10000000 y\n | command grep y >/dev/null
________________________________________________________
Executed in 805.98 millis fish external
usr time 798.88 millis 763.88 millis 34.99 millis
sys time 141.22 millis 40.20 millis 101.02 millis
The time after "Executed in" is what is known as the "wall-clock time".
It is simply a measure of how long it took from the start of the
command until it finished. Typically it is reasonably close to
CMD_DURATION, except for a slight skew because the two are taken at
slightly different times.
The other times are all measures of CPU time. That means they measure
how long the CPU was used in this part, and they count multiple cores
separately. So a program with four threads using all CPU for a second
will have a time of 4 seconds.
The "usr" time is how much CPU time was spent inside the program
itself, the "sys" time is how long was spent in the kernel on behalf of
that program.
The "fish" time is how much CPU was spent in fish, the "external" time
how much was spent in external commands.
So in this example, since string is a builtin, everything that string
repeat did is accounted to fish. Any time it spends doing syscalls like
write() is accounted for in the fish/sys time.
And grep here is explicitly invoked as an external command, so its
times will be counted in the "external" column.
Note that, as in this example, the CPU times can add up to more than
the execution time. This is because things can be done in parallel -
grep can match while string repeat writes.
Example
(for obvious reasons exact results will vary on your system)
>_ time sleep 1s
________________________________________________________
Executed in 1,01 secs fish external
usr time 2,32 millis 0,00 micros 2,32 millis
sys time 0,88 millis 877,00 micros 0,00 millis
>_ time for i in 1 2 3; sleep 1s; end
________________________________________________________
Executed in 3,01 secs fish external
usr time 9,16 millis 2,94 millis 6,23 millis
sys time 0,23 millis 0,00 millis 0,23 millis
Inline variable assignments need to follow the time keyword:
>_ time a_moment=1.5m sleep $a_moment
________________________________________________________
Executed in 90.00 secs fish external
usr time 4.62 millis 4.62 millis 0.00 millis
sys time 2.35 millis 0.41 millis 1.95 millis
trap - perform an action when the shell receives a signal
Synopsis
trap [OPTIONS] [[ARG] REASON ... ]
Description
NOTE: This page documents the fish builtin trap. To see the
documentation on any non-fish versions, use command man trap.
trap is a wrapper around the fish event delivery framework. It exists
for backwards compatibility with POSIX shells. For other uses, it is
recommended to define an event handler.
The following parameters are available:
ARG Command to be executed on signal delivery.
REASON Name of the event to trap. For example, a signal like INT or
SIGINT, or the special symbol EXIT.
-l or --list-signals
Prints a list of signal names.
-p or --print
Prints all defined signal handlers.
-h or --help
Displays help about using this command.
If ARG and REASON are both specified, ARG is the command to be executed
when the event specified by REASON occurs (e.g., the signal is
delivered).
If ARG is absent (and there is a single REASON) or -, each specified
signal is reset to its original disposition (the value it had upon
entrance to the shell). If ARG is the null string the signal specified
by each REASON is ignored by the shell and by the commands it invokes.
If ARG is not present and -p has been supplied, then the trap commands
associated with each REASON are displayed. If no arguments are supplied
or if only -p is given, trap prints the list of commands associated
with each signal.
Signal names are case insensitive and the SIG prefix is optional.
Trapping a signal will prevent fish from exiting in response to that
signal.
The exit status is 1 if any REASON is invalid; otherwise trap returns
0.
Example
trap "status --print-stack-trace" SIGUSR1
# Prints a stack trace each time the SIGUSR1 signal is sent to the shell.
true - return a successful result
Synopsis
true
Description
true sets the exit status to 0.
: (a single colon) is an alias for the true command.
See Also
o false command
o $status variable
type - locate a command and describe its type
Synopsis
type [OPTIONS] NAME [...]
Description
NOTE: This page documents the fish builtin type. To see the
documentation on any non-fish versions, use command man type.
With no options, type indicates how each NAME would be interpreted if
used as a command name.
The following options are available:
-a or --all
Prints all of possible definitions of the specified names.
-s or --short
Don't print function definitions when used with no options or
with -a/--all.
-f or --no-functions
Suppresses function lookup.
-t or --type
Prints function, builtin, or file if NAME is a shell function,
builtin, or disk file, respectively.
-p or --path
Prints the path to NAME if NAME resolves to an executable file
in PATH, the path to the script containing the definition of the
function NAME if NAME resolves to a function loaded from a file
on disk (i.e. not interactively defined at the prompt), or
nothing otherwise.
-P or --force-path
Returns the path to the executable file NAME, presuming NAME is
found in the PATH environment variable, or nothing otherwise.
--force-path explicitly resolves only the path to executable
files in PATH, regardless of whether NAME is shadowed by a
function or builtin with the same name.
-q or --query
Suppresses all output; this is useful when testing the exit
status. For compatibility with old fish versions this is also
--quiet.
-h or --help
Displays help about using this command.
The -q, -p, -t and -P flags (and their long flag aliases) are mutually
exclusive. Only one can be specified at a time.
type returns 0 if at least one entry was found, 1 otherwise, and 2 for
invalid options or option combinations.
Example
>_ type fg
fg is a builtin
ulimit - set or get resource usage limits
Synopsis
ulimit [OPTIONS] [LIMIT]
Description
ulimit sets or outputs the resource usage limits of the shell and any
processes spawned by it. If a new limit value is omitted, the current
value of the limit of the resource is printed; otherwise, the specified
limit is set to the new value.
Use one of the following switches to specify which resource limit to
set or report:
-b or --socket-buffers
The maximum size of socket buffers.
-c or --core-size
The maximum size of core files created. By setting this limit to
zero, core dumps can be disabled.
-d or --data-size
The maximum size of a process' data segment.
-e or --nice
Controls the maximum nice value; on Linux, this value is
subtracted from 20 to give the effective value.
-f or --file-size
The maximum size of files created by a process.
-i or --pending-signals
The maximum number of signals that may be queued.
-l or --lock-size
The maximum size that may be locked into memory.
-m or --resident-set-size
The maximum resident set size.
-n or --file-descriptor-count
The maximum number of open file descriptors.
-q or --queue-size
The maximum size of data in POSIX message queues.
-r or --realtime-priority
The maximum realtime scheduling priority.
-s or --stack-size
The maximum stack size.
-t or --cpu-time
The maximum amount of CPU time in seconds.
-u or --process-count
The maximum number of processes available to the current user.
-w or --swap-size
The maximum swap space available to the current user.
-v or --virtual-memory-size
The maximum amount of virtual memory available to the shell.
-y or --realtime-maxtime
The maximum contiguous realtime CPU time in microseconds.
-K or --kernel-queues
The maximum number of kqueues (kernel queues) for the current
user.
-P or --ptys
The maximum number of pseudo-terminals for the current user.
-T or --threads
The maximum number of simultaneous threads for the current user.
Note that not all these limits are available in all operating systems;
consult the documentation for setrlimit in your operating system.
The value of limit can be a number in the unit specified for the
resource or one of the special values hard, soft, or unlimited, which
stand for the current hard limit, the current soft limit, and no limit,
respectively.
If limit is given, it is the new value of the specified resource. If no
option is given, then -f is assumed. Values are in kilobytes, except
for -t, which is in seconds and -n and -u, which are unscaled values.
The exit status is 0 unless an invalid option or argument is supplied,
or an error occurs while setting a new limit.
ulimit also accepts the following options that determine what type of
limit to set:
-H or --hard
Sets hard resource limit.
-S or --soft
Sets soft resource limit.
A hard limit can only be decreased. Once it is set it cannot be
increased; a soft limit may be increased up to the value of the hard
limit. If neither -H nor -S is specified, both the soft and hard limits
are updated when assigning a new limit value, and the soft limit is
used when reporting the current value.
The following additional options are also understood by ulimit:
-a or --all
Prints all current limits.
-h or --help
Displays help about using this command.
The fish implementation of ulimit should behave identically to the
implementation in bash, except for these differences:
o Fish ulimit supports GNU-style long options for all switches.
o Fish ulimit does not support the -p option for getting the pipe size.
The bash implementation consists of a compile-time check that
empirically guesses this number by writing to a pipe and waiting for
SIGPIPE. Fish does not do this because this method of determining
pipe size is unreliable. Depending on bash version, there may also be
further additional limits to set in bash that do not exist in fish.
o Fish ulimit does not support getting or setting multiple limits in
one command, except reporting all values using the -a switch.
Example
ulimit -Hs 64 sets the hard stack size limit to 64 kB.
umask - set or get the file creation mode mask
Synopsis
umask [OPTIONS] [MASK]
Description
NOTE: This page documents the fish builtin umask. To see the
documentation on any non-fish versions, use command man umask.
umask displays and manipulates the "umask", or file creation mode mask,
which is used to restrict the default access to files.
The umask may be expressed either as an octal number, which represents
the rights that will be removed by default, or symbolically, which
represents the only rights that will be granted by default.
Access rights are explained in the manual page for the chmod(1)
program.
With no parameters, the current file creation mode mask is printed as
an octal number.
-S or --symbolic
Prints the umask in symbolic form instead of octal form.
-p or --as-command
Outputs the umask in a form that may be reused as input.
-h or --help
Displays help about using this command.
If a numeric mask is specified as a parameter, the current shell's
umask will be set to that value, and the rights specified by that mask
will be removed from new files and directories by default.
If a symbolic mask is specified, the desired permission bits, and not
the inverse, should be specified. A symbolic mask is a comma separated
list of rights. Each right consists of three parts:
o The first part specifies to whom this set of right applies, and can
be one of u, g, o or a, where u specifies the user who owns the file,
g specifies the group owner of the file, o specific other users
rights and a specifies all three should be changed.
o The second part of a right specifies the mode, and can be one of =, +
or -, where = specifies that the rights should be set to the new
value, + specifies that the specified right should be added to those
previously specified and - specifies that the specified rights should
be removed from those previously specified.
o The third part of a right specifies what rights should be changed and
can be any combination of r, w and x, representing read, write and
execute rights.
If the first and second parts are skipped, they are assumed to be a and
=, respectively. As an example, r,u+w means all users should have read
access and the file owner should also have write access.
Note that symbolic masks currently do not work as intended.
Example
umask 177 or umask u=rw sets the file creation mask to read and write
for the owner and no permissions at all for any other users.
vared - interactively edit the value of an environment variable
Synopsis
vared VARIABLE_NAME
Description
vared is used to interactively edit the value of an environment
variable. Array variables as a whole can not be edited using vared, but
individual list elements can.
The -h or --help option displays help about using this command.
Example
vared PATH[3] edits the third element of the PATH list
wait - wait for jobs to complete
Synopsis
wait [-n | --any] [PID | PROCESS_NAME] ...
Description
NOTE: This page documents the fish builtin wait. To see the
documentation on any non-fish versions, use command man wait.
wait waits for child jobs to complete.
If a PID is specified, the command waits for the job that the process
with that process ID belongs to.
If a PROCESS_NAME is specified, the command waits for the jobs that the
matched processes belong to.
If neither a pid nor a process name is specified, the command waits for
all background jobs.
If the -n or --any flag is provided, the command returns as soon as the
first job completes. If it is not provided, it returns after all jobs
complete.
The -h or --help option displays help about using this command.
Example
sleep 10 &
wait $last_pid
spawns sleep in the background, and then waits until it finishes.
for i in (seq 1 5); sleep 10 &; end
wait
spawns five jobs in the background, and then waits until all of them
finish.
for i in (seq 1 5); sleep 10 &; end
hoge &
wait sleep
spawns five sleep jobs and hoge in the background, and then waits until
all sleeps finish, and doesn't wait for hoge.
while - perform a set of commands multiple times
Synopsis
while CONDITION; COMMANDS; end
Description
while repeatedly executes CONDITION, and if the exit status is 0, then
executes COMMANDS.
The exit status of the while loop is the exit status of the last
iteration of the COMMANDS executed, or 0 if none were executed. (This
matches other shells and is POSIX-compatible.)
You can use and or or for complex conditions. Even more complex control
can be achieved with while true containing a break.
The -h or --help option displays help about using this command.
Example
while test -f foo.txt; or test -f bar.txt ; echo file exists; sleep 10; end
# outputs 'file exists' at 10 second intervals,
# as long as the file foo.txt or bar.txt exists.
Fish for bash users
This is to give you a quick overview if you come from bash (or to a
lesser extent other shells like zsh or ksh) and want to know how fish
differs. Fish is intentionally not POSIX-compatible and as such some of
the things you are used to work differently.
Many things are similar - they both fundamentally expand commandlines
to execute commands, have pipes, redirections, variables, globs, use
command output in various ways. This document is there to quickly show
you the differences.
Command substitutions
Fish spells command substitutions as $(command) or (command), but not
`command`.
In addition, it only splits them on newlines instead of $IFS. If you
want to split on something else, use string split, string split0 or
string collect. If those are used as the last command in a command
substitution the splits they create are carried over. So:
for i in (find . -print0 | string split0)
will correctly handle all possible filenames.
Variables
Fish sets and erases variables with set instead of VAR=VAL and a
variety of separate builtins like declare and unset and export. set
takes options to determine the scope and exportedness of a variable:
# Define $PAGER *g*lobal and e*x*ported,
# so this is like ``export PAGER=less``
set -gx PAGER less
# Define $alocalvariable only locally,
# like ``local alocalvariable=foo``
set -l alocalvariable foo
or to erase variables:
set -e PAGER
VAR=VAL statements are available as environment overrides:
PAGER=cat git log
Fish does not perform word splitting. Once a variable has been set to a
value, that value stays as it is, so double-quoting variable expansions
isn't the necessity it is in bash. [1]
For instance, here's bash
> foo="bar baz"
> printf '"%s"\n' $foo
# will print two lines, because we didn't double-quote
# this is word splitting
"bar"
"baz"
And here is fish:
> set foo "bar baz"
> printf '"%s"\n' $foo
# foo was set as one element,
# so it will be passed as one element, so this is one line
"bar baz"
All variables are "arrays" (we use the term "lists"), and expanding a
variable expands to all its elements, with each element as its own
argument (like bash's "${var[@]}":
> set var "foo bar" banana
> printf %s\n $var
foo bar
banana
Specific elements of a list can be selected:
echo $list[5..7]
The arguments to set are ordinary, so you can also set a variable to
the output of a command:
# Set lines to all the lines in file, one element per line
set lines (cat file)
or a mixture of literal values and output:
> set numbers 1 2 3 (seq 5 8) 9
> printf '%s\n' $numbers
1
2
3
5
6
7
8
9
A = is unnecessary and unhelpful with set - set foo = bar will set the
variable "foo" to two values: "=" and "bar". set foo=bar will print an
error.
See Shell variables for more.
[1] zsh also does not perform word splitting by default (the
SH_WORD_SPLIT option controls this)
Wildcards (globs)
Fish only supports the * and ** glob (and the deprecated ? glob) as
syntax. If a glob doesn't match it fails the command (like with bash's
failglob) unless the command is for, set or count or the glob is used
with an environment override (VAR=* command), in which case it expands
to nothing (like with bash's nullglob option).
Globbing doesn't happen on expanded variables, so:
set foo "*"
echo $foo
will not match any files.
There are no options to control globbing so it always behaves like
that.
The ** glob will match in subdirectories as well. In other shells this
often needs to be turned on with an option, like setopt globstar in
bash.
Unlike bash, fish will also follow symlinks, and will sort the results
in a natural sort, with included numbers compared as numbers. That
means it will sort e.g. music tracks correctly even if they have
numbers like 1 instead of 01.
See Wildcards for more.
Quoting
Fish has two quoting styles: "" and ''. Variables are expanded in
double-quotes, nothing is expanded in single-quotes.
There is no $'', instead the sequences that would transform are
transformed when unquoted:
> echo a\nb
a
b
See Quotes for more.
String manipulation
Fish does not have ${foo%bar}, ${foo#bar} and ${foo/bar/baz}. Instead
string manipulation is done by the string builtin.
For example, to replace "bar" with "baz":
> string replace bar baz "bar luhrmann"
baz luhrmann
It can also split strings:
> string split "," "foo,bar"
foo
bar
Match regular expressions as a replacement for grep:
> echo bababa | string match -r 'aba$'
aba
Pad strings to a given width, with arbitrary characters:
> string pad -c x -w 20 "foo"
xxxxxxxxxxxxxxxxxfoo
Make strings lower/uppercase:
> string lower Foo
foo
> string upper Foo
FOO
repeat strings, trim strings, escape strings or print a string's length
or width (in terminal cells).
Special variables
Some bash variables and their closest fish equivalent:
o $*, $@, $1 and so on: $argv
o $?: $status
o $$: $fish_pid
o $#: No variable, instead use count $argv
o $!: $last_pid
o $0: status filename
o $-: Mostly status is-interactive and status is-login
Process substitution
Instead of <(command) fish uses (command | psub). There is no
equivalent to >(command).
Note that both of these are bashisms, and most things can easily be
expressed without. E.g. instead of:
source (command | psub)
just use:
command | source
as fish's source can read from stdin.
Heredocs
Fish does not have < math 5 / 2
2.5
And also has some functions, like for trigonometry:
> math cos 2 x pi
1
You can pass arguments to math separately like above or in quotes.
Because fish uses () parentheses for command substitutions, quoting is
needed if you want to use them in your expression:
> math '(5 + 2) * 4'
Both * and x are valid ways to spell multiplication, but * needs to be
quoted because it looks like a glob.
Prompts
Fish does not use the $PS1, $PS2 and so on variables. Instead the
prompt is the output of the fish_prompt function, plus the
fish_mode_prompt function if vi mode is enabled. The output of the
fish_right_prompt function is used for the right-sided prompt.
As an example, here's a relatively simple bash prompt:
# <$HOSTNAME> <$PWD in blue>
PS1='\h\[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\e[m\] '
and a rough fish equivalent:
function fish_prompt
set -l prompt_symbol '$'
fish_is_root_user; and set prompt_symbol '#'
echo -s (prompt_hostname) \
(set_color blue) (prompt_pwd) \
(set_color yellow) $prompt_symbol (set_color normal)
end
This shows a few differences:
o Fish provides set_color to color text. It can use the 16 named colors
and also RGB sequences (so you could also use set_color 5555FF)
o Instead of introducing specific escapes like \h for the hostname, the
prompt is simply a function. To achieve the effect of \h, fish
provides helper functions like prompt_hostname, which prints a
shortened version of the hostname.
o Fish offers other helper functions for adding things to the prompt,
like fish_vcs_prompt for adding a display for common version control
systems (git, mercurial, svn), and prompt_pwd for showing a shortened
$PWD (the user's home directory becomes ~ and any path component is
shortened).
The default prompt is reasonably full-featured and its code can be read
via type fish_prompt.
Fish does not have $PS2 for continuation lines, instead it leaves the
lines indented to show that the commandline isn't complete yet.
Blocks and loops
Fish's blocking constructs look a little different. They all start with
a word, end in end and don't have a second starting word:
for i in 1 2 3; do
echo $i
done
# becomes
for i in 1 2 3
echo $i
end
while true; do
echo Weeee
done
# becomes
while true
echo Weeeeeee
end
{
echo Hello
}
# becomes
begin
echo Hello
end
if true; then
echo Yes I am true
else
echo "How is true not true?"
fi
# becomes
if true
echo Yes I am true
else
echo "How is true not true?"
end
foo() {
echo foo
}
# becomes
function foo
echo foo
end
# (bash allows the word "function",
# but this is an extension)
Fish does not have an until. Use while not or while !.
Subshells
Bash has a feature called "subshells", where it will start another
shell process for certain things. That shell will then be independent
and e.g. any changes it makes to variables won't be visible in the main
shell.
This includes things like:
# A list of commands in `()` parentheses
(foo; bar) | baz
# Both sides of a pipe
foo | while read -r bar; do
# This will not be visible outside of the loop.
VAR=VAL
# This background process will not be, either
baz &
done
Fish does not currently have subshells. You will have to find a
different solution. The isolation can usually be achieved by just
scoping variables (with set -l), but if you really do need to run your
code in a new shell environment you can use fish -c 'your code here' to
do so explicitly.
() subshells are often confused with {} grouping, which does not use a
subshell. When you just need to group, you can use begin; end in fish:
(foo; bar) | baz
# when it should really have been:
{ foo; bar; } | baz
# becomes
begin; foo; bar; end | baz
The pipe will simply be run in the same process, so while read loops
can set variables outside:
foo | while read bar
set -g VAR VAL
baz &
end
echo $VAR # will print VAL
jobs # will show "baz"
Subshells are also frequently confused with command substitutions,
which bash writes as `command` or $(command) and fish writes as
$(command) or (command). Bash also uses subshells to implement them.
Builtins and other commands
By now it has become apparent that fish puts much more of a focus on
its builtins and external commands rather than its syntax. So here are
some helpful builtins and their rough equivalent in bash:
o string - this replaces most of the string transformation (${i%foo} et
al) and can also be used instead of grep and sed and such.
o math - this replaces $((i + 1)) arithmetic and can also do floats and
some simple functions (sine and friends).
o argparse - this can handle a script's option parsing, for which bash
would probably use getopt (zsh provides zparseopts).
o count can be used to count things and therefore replaces $# and can
be used instead of wc.
o status provides information about the shell status, e.g. if it's
interactive or what the current linenumber is. This replaces $- and
$BASH_LINENO and other variables.
o seq(1) can be used as a replacement for {1..10} range expansion. If
your OS doesn't ship a seq fish includes a replacement function.
Other facilities
Bash has set -x or set -o xtrace to print all commands that are being
executed. In fish, this would be enabled by setting fish_trace.
Or, if your intention is to profile how long each line of a script
takes, you can use fish --profile - see the page for the fish command.
Tutorial
Why fish?
Fish is a fully-equipped command line shell (like bash or zsh) that is
smart and user-friendly. Fish supports powerful features like syntax
highlighting, autosuggestions, and tab completions that just work, with
nothing to learn or configure.
If you want to make your command line more productive, more useful, and
more fun, without learning a bunch of arcane syntax and configuration
options, then fish might be just what you're looking for!
Getting started
Once installed, just type in fish into your current shell to try it
out!
You will be greeted by the standard fish prompt, which means you are
all set up and can start using fish:
> fish
Welcome to fish, the friendly interactive shell
Type help for instructions on how to use fish
you@hostname ~>
This prompt that you see above is the fish default prompt: it shows
your username, hostname, and working directory. You can customize it,
see how to change your prompt.
From now on, we'll pretend your prompt is just a > to save space.
Learning fish
This tutorial assumes a basic understanding of command line shells and
Unix commands, and that you have a working copy of fish.
If you have a strong understanding of other shells, and want to know
what fish does differently, search for the magic phrase unlike other
shells, which is used to call out important differences.
Or, if you want a quick overview over the differences to other shells
like Bash, see Fish For Bash Users.
For the full, detailed description of how to use fish interactively,
see Interactive Use.
For a comprehensive description of fish's scripting language, see The
Fish Language.
Running Commands
Fish runs commands like other shells: you type a command, followed by
its arguments. Spaces are separators:
> echo hello world
hello world
This runs the command echo with the arguments hello and world. In this
case that's the same as one argument hello world, but in many cases
it's not. If you need to pass an argument that includes a space, you
can escape with a backslash, or quote it using single or double quotes:
> mkdir My\ Files
# Makes a directory called "My Files", with a space in the name
> cp ~/Some\ File 'My Files'
# Copies a file called "Some File" in the home directory to "My Files"
> ls "My Files"
Some File
Getting Help
Run help to open fish's help in a web browser, and man with the page
(like fish-language) to open it in a man page. You can also ask for
help with a specific command, for example, help set to open in a web
browser, or man set to see it in the terminal.
> man set
set - handle shell variables
Synopsis...
To open this section, use help getting-help.
This only works for fish's own documentation for itself and its
built-in commands (the "builtins"). For any other commands on your
system, they should provide their own documentation, often in the man
system. For example man ls should tell you about your computer's ls
command.
Syntax Highlighting
You'll quickly notice that fish performs syntax highlighting as you
type. Invalid commands are colored red by default:
> /bin/mkd
A command may be invalid because it does not exist, or refers to a file
that you cannot execute. When the command becomes valid, it is shown in
a different color:
> /bin/mkdir
Valid file paths are underlined as you type them:
> cat ~/somefi
This tells you that there exists a file that starts with somefi, which
is useful feedback as you type.
These colors, and many more, can be changed by running fish_config, or
by modifying color variables directly.
For example, if you want to disable (almost) all coloring:
fish_config theme choose none
This picks the "none" theme. To see all themes:
fish_config theme show
Just running fish_config will open up a browser interface that allows
you to pick from the available themes.
Autosuggestions
As you type fish will suggest commands to the right of the cursor, in
gray. For example:
> /bin/hostname
It knows about paths and options:
> grep --ignore-case
And history too. Type a command once, and you can re-summon it by just
typing a few letters:
> rsync -avze ssh . myname@somelonghost.com:/some/long/path/doo/dee/doo/dee/doo
To accept the autosuggestion, hit right (->) or ctrl-f. To accept a
single word of the autosuggestion, alt-right (->). If the
autosuggestion is not what you want, just ignore it.
If you don't like autosuggestions, you can disable them by setting
$fish_autosuggestion_enabled to 0:
set -g fish_autosuggestion_enabled 0
Tab Completions
A rich set of tab completions work "out of the box".
Press tab and fish will attempt to complete the command, argument, or
path:
> /pritab => /private/
If there's more than one possibility, it will list them:
> ~/stuff/stab
~/stuff/script.sh (command) ~/stuff/sources/ (directory)
Hit tab again to cycle through the possibilities. The part in
parentheses there (that "command" and "directory") is the completion
description. It's just a short hint to explain what kind of argument it
is.
fish can also complete many commands, like git branches:
> git merge prtab => git merge prompt_designer
> git checkout btab
builtin_list_io_merge (Branch) builtin_set_color (Branch) busted_events (Tag)
Try hitting tab and see what fish can do!
Variables
Like other shells, a dollar sign followed by a variable name is
replaced with the value of that variable:
> echo My home directory is $HOME
My home directory is /home/tutorial
This is known as variable substitution, and it also happens in double
quotes, but not single quotes:
> echo "My current directory is $PWD"
My current directory is /home/tutorial
> echo 'My current directory is $PWD'
My current directory is $PWD
Unlike other shells, fish has an ordinary command to set variables:
set, which takes a variable name, and then its value.
> set name 'Mister Noodle'
> echo $name
Mister Noodle
(Notice the quotes: without them, Mister and Noodle would have been
separate arguments, and $name would have been made into a list of two
elements.)
Unlike other shells, variables are not further split after
substitution:
> mkdir $name
> ls
Mister Noodle
In bash, this would have created two directories "Mister" and "Noodle".
In fish, it created only one: the variable had the value "Mister
Noodle", so that is the argument that was passed to mkdir, spaces and
all.
You can erase (or "delete") a variable with -e or --erase
> set -e MyVariable
> env | grep MyVariable
(no output)
For more, see Variable expansion.
Exports (Shell Variables)
Sometimes you need to have a variable available to an external command,
often as a setting. For example many programs like git or man read the
$PAGER variable to figure out your preferred pager (the program that
lets you scroll text). Other variables used like this include $BROWSER,
$LANG (to configure your language) and $PATH. You'll note these are
written in ALLCAPS, but that's just a convention.
To give a variable to an external command, it needs to be "exported".
This is done with a flag to set, either --export or just -x.
> set -x MyVariable SomeValue
> env | grep MyVariable
MyVariable=SomeValue
It can also be unexported with --unexport or -u.
This works the other way around as well! If fish is started by
something else, it inherits that parents exported variables. So if your
terminal emulator starts fish, and it exports $LANG set to en_US.UTF-8,
fish will receive that setting. And whatever started your terminal
emulator also gave it some variables that it will then pass on unless
it specifically decides not to. This is how fish usually receives the
values for things like $LANG, $PATH and $TERM, without you having to
specify them again.
Exported variables can be local or global or universal - "exported" is
not a scope! Usually you'd make them global via set -gx MyVariable
SomeValue.
For more, see Exporting variables.
Lists
The set command above used quotes to ensure that Mister Noodle was one
argument. If it had been two arguments, then name would have been a
list of length 2. In fact, all variables in fish are really lists,
that can contain any number of values, or none at all.
Some variables, like $PWD, only have one value. By convention, we talk
about that variable's value, but we really mean its first (and only)
value.
Other variables, like $PATH, really do have multiple values. During
variable expansion, the variable expands to become multiple arguments:
> echo $PATH
/usr/bin /bin /usr/sbin /sbin /usr/local/bin
Variables whose name ends in "PATH" are automatically split on colons
to become lists. They are joined using colons when exported to
subcommands. This is for compatibility with other tools, which expect
$PATH to use colons. You can also explicitly add this quirk to a
variable with set --path, or remove it with set --unpath.
Lists cannot contain other lists: there is no recursion. A variable is
a list of strings, full stop.
Get the length of a list with count:
> count $PATH
5
You can append (or prepend) to a list by setting the list to itself,
with some additional arguments. Here we append /usr/local/bin to $PATH:
> set PATH $PATH /usr/local/bin
You can access individual elements with square brackets. Indexing
starts at 1 from the beginning, and -1 from the end:
> echo $PATH
/usr/bin /bin /usr/sbin /sbin /usr/local/bin
> echo $PATH[1]
/usr/bin
> echo $PATH[-1]
/usr/local/bin
You can also access ranges of elements, known as "slices":
> echo $PATH[1..2]
/usr/bin /bin
> echo $PATH[-1..2]
/usr/local/bin /sbin /usr/sbin /bin
You can iterate over a list (or a slice) with a for loop:
for val in $PATH
echo "entry: $val"
end
# Will print:
# entry: /usr/bin/
# entry: /bin
# entry: /usr/sbin
# entry: /sbin
# entry: /usr/local/bin
One particular bit is that you can use lists like Brace expansion. If
you attach another string to a list, it'll combine every element of the
list with the string:
> set mydirs /usr/bin /bin
> echo $mydirs/fish # this is just like {/usr/bin,/bin}/fish
/usr/bin/fish /bin/fish
This also means that, if the list is empty, there will be no argument:
> set empty # no argument
> echo $empty/this_is_gone # prints an empty line
If you quote the list, it will be used as one string and so you'll get
one argument even if it is empty.
For more, see Lists. For more on combining lists with strings (or even
other lists), see cartesian products and Variable expansion.
Wildcards
Fish supports the familiar wildcard *. To list all JPEG files:
> ls *.jpg
lena.jpg
meena.jpg
santa maria.jpg
You can include multiple wildcards:
> ls l*.p*
lena.png
lesson.pdf
The recursive wildcard ** searches directories recursively:
> ls /var/**.log
/var/log/system.log
/var/run/sntp.log
If that directory traversal is taking a long time, you can ctrl-c out
of it.
For more, see Wildcards.
Pipes and Redirections
You can pipe between commands with the usual vertical bar:
> echo hello world | wc
1 2 12
stdin and stdout can be redirected via the familiar < and >. stderr is
redirected with a 2>.
> grep fish < /etc/shells > ~/output.txt 2> ~/errors.txt
To redirect stdout and stderr into one file, you can use &>:
> make &> make_output.txt
For more, see Input and output redirections and Pipes.
Command Substitutions
Command substitutions use the output of one command as an argument to
another. Unlike other shells, fish does not use backticks `` for
command substitutions. Instead, it uses parentheses with or without a
dollar:
> echo In (pwd), running $(uname)
In /home/tutorial, running FreeBSD
A common idiom is to capture the output of a command in a variable:
> set os (uname)
> echo $os
Linux
Command substitutions without a dollar are not expanded within quotes,
so the version with a dollar is simpler:
> touch "testing_$(date +%s).txt"
> ls *.txt
testing_1360099791.txt
Unlike other shells, fish does not split command substitutions on any
whitespace (like spaces or tabs), only newlines. Usually this is a big
help because unix commands operate on a line-by-line basis. Sometimes
it can be an issue with commands like pkg-config that print what is
meant to be multiple arguments on a single line. To split it on spaces
too, use string split.
> printf '%s\n' (pkg-config --libs gio-2.0)
-lgio-2.0 -lgobject-2.0 -lglib-2.0
> printf '%s\n' (pkg-config --libs gio-2.0 | string split -n " ")
-lgio-2.0
-lgobject-2.0
-lglib-2.0
If you need a command substitutions output as one argument, without any
splits, use quoted command substitution:
> echo "first line
second line" > myfile
> set myfile "$(cat myfile)"
> printf '|%s|' $myfile
|first line
second line|
For more, see Command substitution.
Separating Commands (Semicolon)
Like other shells, fish allows multiple commands either on separate
lines or the same line.
To write them on the same line, use the semicolon (";"). That means the
following two examples are equivalent:
echo fish; echo chips
# or
echo fish
echo chips
This is useful interactively to enter multiple commands. In a script
it's easier to read if the commands are on separate lines.
Exit Status
When a command exits, it returns a status code as a non-negative
integer (that's a whole number >= 0).
Unlike other shells, fish stores the exit status of the last command in
$status instead of $?.
> false
> echo $status
1
This indicates how the command fared - 0 usually means success, while
the others signify kinds of failure. For instance fish's set --query
returns the number of variables it queried that weren't set - set
--query PATH usually returns 0, set --query arglbargl boogagoogoo
usually returns 2.
There is also a $pipestatus list variable for the exit statuses [1] of
processes in a pipe.
For more, see The status variable.
[1] or "stati" if you prefer, or "status" if you've time-travelled
from ancient Rome or work as a latin teacher
Combiners (And, Or, Not)
fish supports the familiar && and || to combine commands, and ! to
negate them:
> ./configure && make && sudo make install
Here, make is only executed if ./configure succeeds (returns 0), and
sudo make install is only executed if both ./configure and make
succeed.
fish also supports and, or, and not. The first two are job modifiers
and have lower precedence. Example usage:
> cp file1 file1_bak && cp file2 file2_bak; and echo "Backup successful"; or echo "Backup failed"
Backup failed
As mentioned in the section on the semicolon, this can also be written
in multiple lines, like so:
cp file1 file1_bak && cp file2 file2_bak
and echo "Backup successful"
or echo "Backup failed"
Conditionals (If, Else, Switch)
Use if and else to conditionally execute code, based on the exit status
of a command.
if grep fish /etc/shells
echo Found fish
else if grep bash /etc/shells
echo Found bash
else
echo Got nothing
end
To compare strings or numbers or check file properties (whether a file
exists or is writeable and such), use test, like
if test "$fish" = "flounder"
echo FLOUNDER
end
# or
if test "$number" -gt 5
echo $number is greater than five
else
echo $number is five or less
end
# or
# This test is true if the path /etc/hosts exists
# - it could be a file or directory or symlink (or possibly something else).
if test -e /etc/hosts
echo We most likely have a hosts file
else
echo We do not have a hosts file
end
Combiners can also be used to make more complex conditions, like
if command -sq fish; and grep fish /etc/shells
echo fish is installed and configured
end
For even more complex conditions, use begin and end to group parts of
them.
There is also a switch command:
switch (uname)
case Linux
echo Hi Tux!
case Darwin
echo Hi Hexley!
case FreeBSD NetBSD DragonFly
echo Hi Beastie!
case '*'
echo Hi, stranger!
end
As you see, case does not fall through, and can accept multiple
arguments or (quoted) wildcards.
For more, see Conditions.
Functions
A fish function is a list of commands, which may optionally take
arguments. Unlike other shells, arguments are not passed in "numbered
variables" like $1, but instead in a single list $argv. To create a
function, use the function builtin:
function say_hello
echo Hello $argv
end
say_hello
# prints: Hello
say_hello everybody!
# prints: Hello everybody!
Unlike other shells, fish does not have aliases or special prompt
syntax. Functions take their place. [2]
You can list the names of all functions with the functions builtin
(note the plural!). fish starts out with a number of functions:
> functions
N_, abbr, alias, bg, cd, cdh, contains_seq, dirh, dirs, disown, down-or-search, edit_command_buffer, export, fg, fish_add_path, fish_breakpoint_prompt, fish_clipboard_copy, fish_clipboard_paste, fish_config, fish_default_key_bindings, fish_default_mode_prompt, fish_git_prompt, fish_hg_prompt, fish_hybrid_key_bindings, fish_indent, fish_is_root_user, fish_job_summary, fish_key_reader, fish_md5, fish_mode_prompt, fish_npm_helper, fish_opt, fish_print_git_action, fish_print_hg_root, fish_prompt, fish_sigtrap_handler, fish_svn_prompt, fish_title, fish_update_completions, fish_vcs_prompt, fish_vi_cursor, fish_vi_key_bindings, funced, funcsave, grep, help, history, hostname, isatty, kill, la, ll, ls, man, nextd, open, popd, prevd, prompt_hostname, prompt_pwd, psub, pushd, realpath, seq, setenv, suspend, trap, type, umask, up-or-search, vared, wait
You can see the source for any function by passing its name to
functions:
> functions ls
function ls --description 'List contents of directory'
command ls -G $argv
end
For more, see Functions.
[2] There is a function called alias, but it's just a shortcut to make
functions. fish also provides abbreviations, through the abbr
command.
Loops
While loops:
while true
echo "Loop forever"
end
# Prints:
# Loop forever
# Loop forever
# Loop forever
# yes, this really will loop forever. Unless you abort it with ctrl-c.
For loops can be used to iterate over a list. For example, a list of
files:
for file in *.txt
cp $file $file.bak
end
Iterating over a list of numbers can be done with seq:
for x in (seq 5)
touch file_$x.txt
end
For more, see Loops and blocks.
Prompt
Unlike other shells, there is no prompt variable like PS1. To display
your prompt, fish executes the fish_prompt function and uses its output
as the prompt. And if it exists, fish also executes the
fish_right_prompt function and uses its output as the right prompt.
You can define your own prompt from the command line:
> function fish_prompt; echo "New Prompt % "; end
New Prompt % _
Then, if you are happy with it, you can save it to disk by typing
funcsave fish_prompt. This saves the prompt in
~/.config/fish/functions/fish_prompt.fish. (Or, if you want, you can
create that file manually from the start.)
Multiple lines are OK. Colors can be set via set_color, passing it
named ANSI colors, or hex RGB values:
function fish_prompt
set_color purple
date "+%m/%d/%y"
set_color F00
echo (pwd) '>' (set_color normal)
end
This prompt would look like:
02/06/13
/home/tutorial > _
You can choose among some sample prompts by running fish_config for a
web UI or fish_config prompt for a simpler version inside your
terminal.
$PATH
$PATH is an environment variable containing the directories that fish
searches for commands. Unlike other shells, $PATH is a list, not a
colon-delimited string.
Fish takes care to set $PATH to a default, but typically it is just
inherited from fish's parent process and is set to a value that makes
sense for the system - see Exports.
To prepend /usr/local/bin and /usr/sbin to $PATH, you can write:
> set PATH /usr/local/bin /usr/sbin $PATH
To remove /usr/local/bin from $PATH, you can write:
> set PATH (string match -v /usr/local/bin $PATH)
For compatibility with other shells and external commands, $PATH is a
path variable, and so will be joined with colons (not spaces) when you
quote it:
> echo "$PATH"
/usr/local/sbin:/usr/local/bin:/usr/bin
and it will be exported like that, and when fish starts it splits the
$PATH it receives into a list on colon.
You can do so directly in config.fish, like you might do in other
shells with .profile. See this example.
A faster way is to use the fish_add_path function, which adds given
directories to the path if they aren't already included. It does this
by modifying the $fish_user_paths universal variable, which is
automatically prepended to $PATH. For example, to permanently add
/usr/local/bin to your $PATH, you could write:
> fish_add_path /usr/local/bin
The advantage is that you don't have to go mucking around in files:
just run this once at the command line, and it will affect the current
session and all future instances too. You can also add this line to
config.fish, as it only adds the component if necessary.
Or you can modify $fish_user_paths yourself, but you should be careful
not to append to it unconditionally in config.fish, or it will grow
longer and longer.
Startup (Where's .bashrc?)
Fish starts by executing commands in ~/.config/fish/config.fish. You
can create it if it does not exist.
It is possible to directly create functions and variables in
config.fish file, using the commands shown above. For example:
> cat ~/.config/fish/config.fish
set -x PATH $PATH /sbin/
function ll
ls -lh $argv
end
However, it is more common and efficient to use autoloading functions
and universal variables.
If you want to organize your configuration, fish also reads commands in
.fish files in ~/.config/fish/conf.d/. See Configuration Files for the
details.
Autoloading Functions
When fish encounters a command, it attempts to autoload a function for
that command, by looking for a file with the name of that command in
~/.config/fish/functions/.
For example, if you wanted to have a function ll, you would add a text
file ll.fish to ~/.config/fish/functions:
> cat ~/.config/fish/functions/ll.fish
function ll
ls -lh $argv
end
This is the preferred way to define your prompt as well:
> cat ~/.config/fish/functions/fish_prompt.fish
function fish_prompt
echo (pwd) "> "
end
See the documentation for funced and funcsave for ways to create these
files automatically, and $fish_function_path to control their location.
Universal Variables
A universal variable is a variable whose value is shared across all
instances of fish, now and in the future - even after a reboot. You can
make a variable universal with set -U:
> set -U EDITOR vim
Now in another shell:
> echo $EDITOR
vim
You only need to set universal variables once interactively. There is
no need to add them to your config files. For more details, see
Universal Variables.
Ready for more?
If you want to learn more about fish, there is lots of detailed
documentation, the official gitter channel , an official mailing list
, and the
github page .
Writing your own completions
To specify a completion, use the complete command. complete takes as a
parameter the name of the command to specify a completion for. For
example, to add a completion for the program myprog, start the
completion command with complete -c myprog ...
For a complete description of the various switches accepted by the
complete command, see the documentation for the complete builtin, or
write complete --help inside the fish shell.
To provide a list of possible completions for myprog, use the -a
switch. If myprog accepts the arguments start and stop, this can be
specified as complete -c myprog -a 'start stop'. The argument to the -a
switch is always a single string. At completion time, it will be
tokenized on spaces and tabs, and variable expansion, command
substitution and other forms of parameter expansion will take place:
# If myprog can list the valid outputs with the list-outputs subcommand:
complete -c myprog -l output -a '(myprog list-outputs)'
fish has a special syntax to support specifying switches accepted by a
command. The switches -s, -l and -o are used to specify a short switch
(single character, such as -l), a gnu style long switch (such as
--color) and an old-style long switch (with one -, like -shuffle),
respectively. If the command 'myprog' has an option that can be written
as -o or --output, that is:
complete -c myprog -s o -l output
If this option takes an optional argument, you would also add
--argument or -a, and give that the possible arguments:
complete -c myprog -s o -l output -a "yes no"
This offers the arguments "yes" and "no" for:
> myprog -o
> myprog --output=
By default, option arguments are optional, so the candidates are only
offered directly attached like that, so they aren't given in this case:
> myprog -o
Usually options require a parameter, so you would give
--require-parameter / -r:
complete -c myprog -s o -l output -ra "yes no"
which offers yes/no in these cases:
> myprog -o
> myprog --output=
> myprog -o
> myprog --output
Fish will also offer files by default, in addition to the arguments you
specified. You would either inhibit file completion for a single
option:
complete -c myprog -s o -l output --no-files -ra "yes no"
or with a specific condition:
complete -c myprog -f --condition '__fish_seen_subcommand_from somesubcommand'
or you can disable file completions globally for the command:
complete -c myprog -f
If you have disabled them globally, you can enable them just for a
specific condition or option with the --force-files / -F option:
# Disable files by default
complete -c myprog -f
# but reenable them for --config-file
complete -c myprog -l config-file --force-files -r
As a more comprehensive example, here's a commented excerpt of the
completions for systemd's timedatectl:
# All subcommands that timedatectl knows - this is useful for later.
set -l commands status set-time set-timezone list-timezones set-local-rtc set-ntp
# Disable file completions for the entire command
# because it does not take files anywhere
# Note that this can be undone by using "-F".
#
# File completions also need to be disabled
# if you want to have more control over what files are offered
# (e.g. just directories, or just files ending in ".mp3").
complete -c timedatectl -f
# This line offers the subcommands
# -"status",
# -"set-timezone",
# -"set-time"
# -"list-timezones"
# if no subcommand has been given so far.
#
# The `-n`/`--condition` option takes script as a string, which it executes.
# If it returns true, the completion is offered.
# Here the condition is the `__fish_seen_subcommands_from` helper function.
# It returns true if any of the given commands is used on the commandline,
# as determined by a simple heuristic.
# For more complex uses, you can write your own function.
# See e.g. the git completions for an example.
#
complete -c timedatectl -n "not __fish_seen_subcommand_from $commands" \
-a "status set-time set-timezone list-timezones"
# If the "set-timezone" subcommand is used,
# offer the output of `timedatectl list-timezones` as completions.
# Each line of output is used as a separate candidate,
# and anything after a tab is taken as the description.
# It's often useful to transform command output with `string` into that form.
complete -c timedatectl -n "__fish_seen_subcommand_from set-timezone" \
-a "(timedatectl list-timezones)"
# Completion candidates can also be described via `-d`,
# which is useful if the description is constant.
# Try to keep these short, because that means the user gets to see more at once.
complete -c timedatectl -n "not __fish_seen_subcommand_from $commands" \
-a "set-local-rtc" -d "Maintain RTC in local time"
# We can also limit options to certain subcommands by using conditions.
complete -c timedatectl -n "__fish_seen_subcommand_from set-local-rtc" \
-l adjust-system-clock -d 'Synchronize system clock from the RTC'
# These are simple options that can be used everywhere.
complete -c timedatectl -s h -l help -d 'Print a short help text and exit'
complete -c timedatectl -l version -d 'Print a short version string and exit'
complete -c timedatectl -l no-pager -d 'Do not pipe output into a pager'
For examples of how to write your own complex completions, study the
completions in /usr/share/fish/completions. (The exact path depends on
your chosen installation prefix and may be slightly different)
Useful functions for writing completions
fish ships with several functions that may be useful when writing
command-specific completions. Most of these function names begin with
the string __fish_. Such functions are internal to fish and their name
and interface may change in future fish versions. A few of these
functions are described here.
Functions beginning with the string __fish_print_ print a newline
separated list of strings. For example, __fish_print_filesystems prints
a list of all known file systems. Functions beginning with
__fish_complete_ print out a newline separated list of completions with
descriptions. The description is separated from the completion by a tab
character.
o __fish_complete_directories STRING DESCRIPTION performs path
completion on STRING, allowing only directories, and giving them the
description DESCRIPTION.
o __fish_complete_path STRING DESCRIPTION performs path completion on
STRING, giving them the description DESCRIPTION.
o __fish_complete_groups prints a list of all user groups with the
groups members as description.
o __fish_complete_pids prints a list of all processes IDs with the
command name as description.
o __fish_complete_suffix SUFFIX performs file completion but sorts
files ending in SUFFIX first. This is useful in conjunction with
complete --keep-order.
o __fish_complete_users prints a list of all users with their full name
as description.
o __fish_print_filesystems prints a list of all known file systems.
Currently, this is a static list, and not dependent on what file
systems the host operating system actually understands.
o __fish_print_hostnames prints a list of all known hostnames. This
function searches the fstab for nfs servers, ssh for known hosts and
checks the /etc/hosts file.
o __fish_print_interfaces prints a list of all known network
interfaces.
Where to put completions
Completions can be defined on the commandline or in a configuration
file, but they can also be automatically loaded. Fish automatically
searches through any directories in the list variable
$fish_complete_path, and any completions defined are automatically
loaded when needed. A completion file must have a filename consisting
of the name of the command to complete and the suffix .fish.
By default, Fish searches the following for completions, using the
first available file that it finds:
o A directory for end-users to keep their own completions, usually
~/.config/fish/completions (controlled by the XDG_CONFIG_HOME
environment variable);
o A directory for systems administrators to install completions for all
users on the system, usually /etc/fish/completions;
o A user-specified directory for third-party vendor completions,
usually ~/.local/share/fish/vendor_completions.d (controlled by the
XDG_DATA_HOME environment variable);
o A directory for third-party software vendors to ship their own
completions for their software, usually
/usr/share/fish/vendor_completions.d;
o The completions shipped with fish, usually installed in
/usr/share/fish/completions; and
o Completions automatically generated from the operating system's
manual, usually stored in ~/.cache/fish/generated_completions
(controlled by XDG_CACHE_HOME environment variable).
These paths are controlled by parameters set at build, install, or run
time, and may vary from the defaults listed above.
This wide search may be confusing. If you are unsure, your completions
probably belong in ~/.config/fish/completions.
If you have written new completions for a common Unix command, please
consider sharing your work by submitting it via the instructions in
Further help and development.
If you are developing another program and would like to ship
completions with your program, install them to the "vendor" completions
directory. As this path may vary from system to system, the pkgconfig
framework should be used to discover this path with the output of
pkg-config --variable completionsdir fish.
Writing your own prompt
WARNING:
This document uses formatting to show what a prompt would look like.
If you are viewing this in the man page, you probably want to switch
to looking at the html version instead. Run help custom-prompt to
view it in a web browser.
Fish ships a number of prompts that you can view with the fish_config
command, and many users have shared their prompts online.
However, you can also write your own, or adjust an existing prompt.
This is a good way to get used to fish's scripting language.
Unlike other shells, fish's prompt is built by running a function -
fish_prompt. Or, more specifically, three functions:
o fish_prompt, which is the main prompt function
o fish_right_prompt, which is shown on the right side of the terminal.
o fish_mode_prompt, which is shown if vi mode is used.
These functions are run, and whatever they print is displayed as the
prompt (minus one trailing newline).
Here, we will just be writing a simple fish_prompt.
Our first prompt
Let's look at a very simple example:
function fish_prompt
echo $PWD '>'
end
This prints the current working directory (PWD) and a > symbol to show
where the prompt ends. The > is quoted because otherwise it would
signify a redirection.
Because we've used echo, it adds spaces between the two so it ends up
looking like (assuming _ is your cursor):
/home/tutorial >_
Formatting
echo adds spaces between its arguments. If you don't want those, you
can use string join like this:
function fish_prompt
string join '' -- $PWD '>'
end
The -- indicates to string that no options can come after it, in case
we extend this with something that can start with a -.
There are other ways to remove the space, including echo -s and printf.
Adding color
This prompt is functional, but a bit boring. We could add some color.
Fortunately, fish offers the set_color command, so you can do:
echo (set_color red)foo
set_color can also handle RGB colors like set_color 23b455, and other
formatting options including bold and italics.
So, taking our previous prompt and adding some color:
function fish_prompt
string join '' -- (set_color green) $PWD (set_color normal) '>'
end
A "normal" color tells the terminal to go back to its normal formatting
options.
set_color works by producing an escape sequence, which is a special
piece of text that terminals interpret as instructions - for example,
to change color. So set_color red produces the same effect as:
echo \e\[31m
Although you can write your own escape sequences by hand, it's much
easier to use set_color.
Shortening the working directory
This is fine, but our PWD can be a bit long, and we are typically only
interested in the last few directories. We can shorten this with the
prompt_pwd helper that will give us a shortened working directory:
function fish_prompt
string join '' -- (set_color green) (prompt_pwd) (set_color normal) '>'
end
prompt_pwd takes options to control how much to shorten. For instance,
if we want to display the last two directories, we'd use prompt_pwd
--full-length-dirs 2:
function fish_prompt
string join '' -- (set_color green) (prompt_pwd --full-length-dirs 2) (set_color normal) '>'
end
With a current directory of "/home/tutorial/Music/Lena
Raine/Oneknowing", this would print
~/M/Lena Raine/Oneknowing>_
Status
One important bit of information that every command returns is the
status. This is a whole number from 0 to 255, and usually it is used as
an error code - 0 if the command returned successfully, or a number
from 1 to 255 if not.
It's useful to display this in your prompt, but showing it when it's 0
seems kind of wasteful.
First of all, since every command (except for set) changes the status,
you need to store it for later use as the first thing in your prompt.
Use a local variable so it will be confined to your prompt function:
set -l last_status $status
And after that, you can set a string if it is not zero:
# Prompt status only if it's not 0
set -l stat
if test $last_status -ne 0
set stat (set_color red)"[$last_status]"(set_color normal)
end
And to print it, we add it to our string join:
string join '' -- (set_color green) (prompt_pwd) (set_color normal) $stat '>'
If $last_status was 0, $stat is empty, and so it will simply disappear.
So our entire prompt is now:
function fish_prompt
set -l last_status $status
# Prompt status only if it's not 0
set -l stat
if test $last_status -ne 0
set stat (set_color red)"[$last_status]"(set_color normal)
end
string join '' -- (set_color green) (prompt_pwd) (set_color normal) $stat '>'
end
And it looks like:
~/M/L/Oneknowing[1]>_
after we run false (which returns 1).
Save the prompt
Once you are happy with your prompt, you can save it with funcsave
fish_prompt (see funcsave - save the definition of a function to the
user's autoload directory) or write it to
~/.config/fish/functions/fish_prompt.fish yourself.
If you want to edit it again, open that file or use funced fish_prompt
(see funced - edit a function interactively).
Where to go from here?
We have now built a simple but working and usable prompt, but of course
more can be done.
o
Fish offers more helper functions:
o prompt_login to describe the user/hostname/container or
prompt_hostname to describe just the host
o fish_is_root_user to help with changing the symbol for root.
o fish_vcs_prompt to show version control information (or
fish_git_prompt / fish_hg_prompt / fish_svn_prompt to limit
it to specific systems)
o You can add a right prompt by changing fish_right_prompt or a vi mode
prompt by changing fish_mode_prompt.
o
Some prompts have interesting or advanced features
o Add the time when the prompt was printed
o Show various integrations like python's venv
o Color the parts differently.
You can look at fish's sample prompts for inspiration. Open up
fish_config, find one you like and pick it. For example:
fish_config prompt show # <- shows all the sample prompts
fish_config prompt choose disco # <- this picks the "disco" prompt for this session
funced fish_prompt # <- opens fish_prompt in your editor, and reloads it once the editor exits
Design
This is a description of the design principles that have been used to
design fish. The fish design has three high level goals. These are:
1. Everything that can be done in other shell languages should be
possible to do in fish, though fish may rely on external commands in
doing so.
2. Fish should be user-friendly, but not at the expense of
expressiveness. Most tradeoffs between power and ease of use can be
avoided with careful design.
3. Whenever possible without breaking the above goals, fish should
follow POSIX.
To achieve these high-level goals, the fish design relies on a number
of more specific design principles. These are presented below, together
with a rationale and a few examples for each.
The law of orthogonality
The shell language should have a small set of orthogonal features. Any
situation where two features are related but not identical, one of them
should be removed, and the other should be made powerful and general
enough to handle all common use cases of either feature.
Rationale: Related features make the language larger, which makes it
harder to learn. It also increases the size of the source code, making
the program harder to maintain and update.
Examples:
o Here documents are too similar to using echo inside of a pipeline.
o Subshells, command substitution and process substitution are strongly
related. fish only supports command substitution, the others can be
achieved either using a block or the psub shellscript function.
o Having both aliases and functions is confusing, especially since both
of them have limitations and problems. fish functions have none of
the drawbacks of either syntax.
o The many Posix quoting styles are silly, especially $.
The law of responsiveness
The shell should attempt to remain responsive to the user at all times,
even in the face of contended or unresponsive filesystems. It is only
acceptable to block in response to a user initiated action, such as
running a command.
Rationale: Bad performance increases user-facing complexity, because it
trains users to recognize and route around slow use cases. It is also
incredibly frustrating.
Examples:
o Features like syntax highlighting and autosuggestions must perform
all of their disk I/O asynchronously.
o Startup should minimize forks and disk I/O, so that fish can be
started even if the system is under load.
Configurability is the root of all evil
Every configuration option in a program is a place where the program is
too stupid to figure out for itself what the user really wants, and
should be considered a failure of both the program and the programmer
who implemented it.
Rationale: Different configuration options are a nightmare to maintain,
since the number of potential bugs caused by specific configuration
combinations quickly becomes an issue. Configuration options often
imply assumptions about the code which change when reimplementing the
code, causing issues with backwards compatibility. But mostly,
configuration options should be avoided since they simply should not
exist, as the program should be smart enough to do what is best, or at
least a good enough approximation of it.
Examples:
o Fish allows the user to set various syntax highlighting colors. This
is needed because fish does not know what colors the terminal uses by
default, which might make some things unreadable. The proper solution
would be for text color preferences to be defined centrally by the
user for all programs, and for the terminal emulator to send these
color properties to fish.
o Fish does not allow you to set the number of history entries,
different language substyles or any number of other common shell
configuration options.
A special note on the evils of configurability is the long list of very
useful features found in some shells, that are not turned on by
default. Both zsh and bash support command-specific completions, but no
such completions are shipped with bash by default, and they are turned
off by default in zsh. Other features that zsh supports that are
disabled by default include tab-completion of strings containing
wildcards, a sane completion pager and a history file.
The law of user focus
When designing a program, one should first think about how to make an
intuitive and powerful program. Implementation issues should only be
considered once a user interface has been designed.
Rationale: This design rule is different than the others, since it
describes how one should go about designing new features, not what the
features should be. The problem with focusing on what can be done, and
what is easy to do, is that too much of the implementation is exposed.
This means that the user must know a great deal about the underlying
system to be able to guess how the shell works, it also means that the
language will often be rather low-level.
Examples:
o There should only be one type of input to the shell, lists of
commands. Loops, conditionals and variable assignments are all
performed through regular commands.
o The differences between built-in commands and shellscript functions
should be made as small as possible. Built-ins and shellscript
functions should have exactly the same types of argument expansion as
other commands, should be possible to use in any position in a
pipeline, and should support any I/O redirection.
o Instead of forking when performing command substitution to provide a
fake variable scope, all fish commands are performed from the same
process, and fish instead supports true scoping.
o All blocks end with the end built-in.
The law of discoverability
A program should be designed to make its features as easy as possible
to discover for the user.
Rationale: A program whose features are discoverable turns a new user
into an expert in a shorter span of time, since the user will become an
expert on the program simply by using it.
The main benefit of a graphical program over a command-line-based
program is discoverability. In a graphical program, one can discover
all the common features by simply looking at the user interface and
guessing what the different buttons, menus and other widgets do. The
traditional way to discover features in command-line programs is
through manual pages. This requires both that the user starts to use a
different program, and then they remember the new information until the
next time they use the same program.
Examples:
o Everything should be tab-completable, and every tab completion should
have a description.
o Every syntax error and error in a built-in command should contain an
error message describing what went wrong and a relevant help page.
Whenever possible, errors should be flagged red by the syntax
highlighter.
o The help manual should be easy to read, easily available from the
shell, complete and contain many examples
o The language should be uniform, so that once the user understands the
command/argument syntax, they will know the whole language, and be
able to use tab-completion to discover new features.
Release notes
fish 4.0.0 (released February 27, 2025)
fish's core code has been ported from C++ to Rust (#9512
). This means a
large change in dependencies and how to build fish. However, there
should be no direct impact on users. Packagers should see the For
Distributors section at the end.
Notable backwards-incompatible changes
o As part of a larger binding rework, bind gained a new key notation.
In most cases the old notation should keep working, but in rare cases
you may have to change a bind invocation to use the new notation.
See below for details.
o ctrl-c now calls a new bind function called clear-commandline. The
old behavior, which leaves a "^C" marker, is available as
cancel-commandline (#10935 )
o random will produce different values from previous versions of fish
when used with the same seed, and will work more sensibly with small
seed numbers. The seed was never guaranteed to give the same result
across systems, so we do not expect this to have a large impact
(#9593 ).
o Variables in command position that expand to a subcommand keyword are
now forbidden to fix a likely user error. For example, set editor
command emacs; $editor is no longer allowed (#10249
).
o functions --handlers will now list handlers in a different order.
Now it is definition order, first to last, where before it was last
to first. This was never specifically defined, and we recommend not
relying on a specific order (#9944 ).
o The qmark-noglob feature, introduced in fish 3.0, is enabled by
default. That means ? will no longer act as a single-character glob.
You can, for the time being, turn it back on by adding
no-qmark-noglob to fish_features and restarting fish:
set -Ua fish_features no-qmark-noglob
The flag will eventually be made read-only, making it impossible to
turn off.
o Terminals that fail to ignore unrecognized OSC or CSI sequences may
display garbage. We know cool-retro-term and emacs' ansi-term are
affected, but most mainstream terminals are not.
o fish no longer searches directories from the Windows system/user
$PATH environment variable for Linux executables. To execute Linux
binaries by name (i.e. not with a relative or absolute path) from a
Windows folder, make sure the /mnt/c/... path is explicitly added to
$fish_user_paths and not just automatically appended to $PATH by
wsl.exe (#10506 ).
o Under Microsoft Windows Subsystem for Linux 1 (not WSL 2),
backgrounded jobs that have not been disowned and do not terminate on
their own after a SIGHUP + SIGCONT sequence will be explicitly killed
by fish on exit (after the usual prompt to close or disown them) to
work around a WSL 1 deficiency that sees backgrounded processes that
run into SIGTTOU remain in a suspended state indefinitely (#5263
). The
workaround is to explicitly disown processes you wish to outlive the
shell session.
Notable improvements and fixes
o fish now requests XTerm's modifyOtherKeys keyboard encoding and kitty
keyboard protocol's progressive enhancements (#10359 ). Depending on terminal support, this
allows to binding more key combinations, including arbitrary
combinations of modifiers ctrl, alt and shift, and distinguishing
(for example) ctrl-i from tab.
Additionally, bind now supports a human-readable syntax in addition
to byte sequences. This includes modifier names, and names for keys
like enter and backspace. For example
o bind up 'do something' binds the up-arrow key instead of a two-key
sequence ("u" and then "p")
o bind ctrl-x,alt-c 'do something' binds a sequence of two keys.
Any key argument that starts with an ASCII control character (like \e
or \cX) or is up to 3 characters long, not a named key, and does not
contain , or - will be interpreted in the old syntax to keep
compatibility for the majority of bindings.
Keyboard protocols can be turned off by disabling the
"keyboard-protocols" feature flag:
set -Ua fish_features no-keyboard-protocols
This is a temporary measure to work around buggy terminals (#11056
), which
appear to be relatively rare. Use this if something like "=0" or
"=5u" appears in your commandline mysteriously.
o fish can now be built as a self-installing binary (#10367
). That means
it can be easily built on one system and copied to another, where it
can extract supporting files. To do this, run:
cargo install --path . # in a clone of the fish repository
# or `cargo build --release` and copy target/release/fish{,_indent,_key_reader} wherever you want
The first time it runs interactively, it will extract all the data
files to ~/.local/share/fish/install/. A specific path can be used
for the data files with fish --install=PATH To uninstall, remove the
fish binaries and that directory.
This build system is experimental; the main build system, using
cmake, remains the recommended approach for packaging and
installation to a prefix.
o A new function fish_should_add_to_history can be overridden to decide
whether a command should be added to the history (#10302
).
o Bindings can now mix special input functions and shell commands, so
bind ctrl-g expand-abbr "commandline -i \n" works as expected (#8186
).
o Special input functions run from bindings via commandline -f are now
applied immediately, instead of after the currently executing binding
(#3031 , #10126
). For
example, commandline -i foo; commandline | grep foo succeeds now.
o Undo history is no longer truncated after every command, but kept for
the lifetime of the shell process.
o The ctrl-r history search now uses glob syntax (#10131
).
o The ctrl-r history search now operates only on the line or command
substitution at cursor, making it easier to combine commands from
history (#9751 ).
o Abbreviations can now be restricted to specific commands. For
instance:
abbr --add --command git back 'reset --hard HEAD^'
will expand "back" to reset --hard HEAD^, but only when the command
is git (#9411 ).
Deprecations and removed features
o commandline --tokenize (short option -o) has been deprecated in favor
of commandline --tokens-expanded (short option -x) which expands
variables and other shell syntax, removing the need to use eval in
completion scripts (#10212 ).
o Two new feature flags:
o remove-percent-self (see status features) disables PID expansion of
%self, which has been supplanted by $fish_pid (#10262
).
o test-require-arg disables test's one-argument mode. That means test
-n without an additional argument will return false, test -z will
keep returning true. Any other option without an argument, anything
that is not an option and no argument will be an error. This also
goes for [, test's alternate name. This is a frequent source of
confusion and so we are breaking with POSIX explicitly in this
regard. In addition to the feature flag, there is a debug category
"deprecated-test". Running fish with fish -d deprecated-test will
show warnings whenever a test invocation that would change is used.
(#10365 ).
These can be enabled with:
set -Ua fish_features remove-percent-self test-require-arg
We intend to enable them by default in future, and after that
eventually make them read-only.
o Specifying key names as terminfo names (using the bind -k syntax) is
deprecated and may be removed in a future version.
o When a terminal pastes text into fish using bracketed paste, fish
used to switch to a special paste bind mode. This bind mode has been
removed. The behavior on paste is no longer configurable.
o When an interactive fish is stopped or terminated by a signal that
cannot be caught (SIGSTOP or SIGKILL), it may leave the terminal in a
state where keypresses with modifiers are sent as CSI u sequences,
instead of traditional control characters or escape sequences that
are recognized by Readline and compatible programs, such as bash and
python. If this happens, you can use the reset command from ncurses
to restore the terminal state.
o fish_key_reader --verbose no longer shows timing information.
o Terminal information is no longer read from hashed terminfo
databases, or termcap databases (#10269 ). The vast majority of systems use a
non-hashed terminfo database, which is still supported.
o source returns an error if used without a filename or
pipe/redirection (#10774 ).
Scripting improvements
o for loops will no longer remember local variables from the previous
iteration (#10525 ).
o A new history append subcommand appends a command to the history,
without executing it (#4506 ).
o A new redirection: /path/to/file will try opening the file as
input, and if it doesn't succeed silently uses /dev/null instead.
This can help with checks like test -f /path/to/file; and string
replace foo bar < /path/to/file. (#10387 )
o A new option commandline --tokens-raw prints a list of tokens without
any unescaping (#10212 ).
o A new option commandline --showing-suggestion tests whether an
autosuggestion is currently displayed (#10586
).
o functions and type now show that a function was copied and its
source, rather than solely Defined interactively (#6575
).
o Stack trace now shows line numbers for copied functions (#6575
).
o foo & && bar is now a syntax error, like in other shells (#9911
).
o if -e foo; end now prints a more accurate error (#10000
).
o cd into a directory that is not readable but accessible (permissions
--x) is now possible (#10432 ).
o An integer overflow in string repeat leading to a near-infinite loop
has been fixed (#9899 ).
o string shorten behaves better in the presence of non-printable
characters, including fixing an integer overflow that shortened
strings more than intended (#9854 ).
o string pad no longer allows non-printable characters as padding
(#9854 ).
o string repeat now allows omission of -n when the first argument is an
integer (#10282 ).
o string match and replace have a new --max-matches option to return as
soon as the specified number of matches have been identified, which
can improve performance in scripts (#10587 ).
o functions --handlers-type caller-exit once again lists functions
defined as function --on-job-exit caller, rather than them being
listed by functions --handlers-type process-exit.
o A new set --no-event option sets or erases variables without
triggering a variable event. This can be useful to change a variable
in an event handler (#10480 ).
o Commas in command substitution output are no longer used as
separators in brace expansion, preventing a surprising expansion in
some cases (#5048 ).
o Universal variables can now store strings containing invalid UTF-8
(#10313 ).
o A new path basename -E option that causes it to return the basename
("filename" with the directory prefix removed) with the final
extension (if any) also removed. This is a shorter version of path
change-extension "" (path basename $foo) (#10521
).
o A new math --scale-mode option to select truncate, round, floor,
ceiling as you wish; the default value is truncate. (#9117
).
o random is now less strict about its arguments, allowing a start
larger or equal to the end. (#10879 )
o function --argument-names now produces an error if a read-only
variable name is used, rather than simply ignoring it (#10842
).
o Tilde expansion in braces (that is, {~,}) works correctly (#10610
).
Interactive improvements
o Autosuggestions were sometimes not shown after recalling a line from
history, which has been fixed (#10287 ).
o Up-arrow search matches -- which are highlighted in reverse colors --
are no longer syntax-highlighted, to fix bad contrast with the search
match highlighting.
o Command abbreviations (those with --position command or without a
--position) now also expand after decorators like command (#10396
).
o Abbreviations now expand after process separators like ; and |. This
fixes a regression in version 3.6 (#9730 ).
o When exporting interactively defined functions (using type, functions
or funcsave) the function body is now indented, to match the
interactive command line editor (#8603 ).
o ctrl-x (fish_clipboard_copy) on multiline commands now includes
indentation (#10437 ).
o ctrl-v (fish_clipboard_paste) now strips ASCII control characters
from the pasted text. This is consistent with normal keyboard input
(#5274 ).
o When a command like fg %2 fails to find the given job, it no longer
behaves as if no job spec was given (#9835 ).
o Redirection in command position like >echo is now highlighted as
error (#8877 ).
o fish_vi_cursor now works properly inside the prompt created by
builtin read (#10088 ).
o fish no longer fails to open a FIFO if interrupted by a terminal
resize signal (#10250 ).
o read --help and friends no longer ignore redirections. This fixes a
regression in version 3.1 (#10274 ).
o Measuring a command with time now considers the time taken for
command substitution (#9100 ).
o fish_add_path now automatically enables verbose mode when used
interactively (in the command line), in an effort to be clearer about
what it does (#10532 ).
o fish no longer adopts TTY modes of failed commands (#10603
).
o complete -e cmd now prevents autoloading completions for cmd (#6716
).
o fish's default color scheme no longer uses the color "blue", as it
has bad contrast against the background in a few terminal's default
palettes (#10758 , #10786 ) The color scheme will not be upgraded for
existing installs. If you want, you should select it again via
fish_config.
o Command lines which are larger than the terminal are now displayed
correctly, instead of multiple blank lines being displayed (#7296
).
o Prompts that use external commands will no longer produce an infinite
loop if the command crashes (#9796 ).
o Undo (ctrl-z) restores the cursor position too (#10838
).
o The output of jobs shows "-" for jobs that have the same process
group ID as the fish process, rather than "-2" (#10833
).
o Job expansion (%1 syntax) works properly for jobs that are a mixture
of external commands and functions (#10832 ).
o Command lines which have more lines than the terminal can be
displayed and edited correctly (#10827 ).
o Functions that have been erased are no longer highlighted as valid
commands (#10866 ).
o not, time, and variable assignments (that is not time a=b env) is
correctly recognized as valid syntax (#10890
).
o The Web-based configuration removes old right-hand-side prompts
again, fixing a regression in fish 3.4.0 (#10675
).
o Further protection against programs which crash and leave the
terminal in an inconsistent state (#10834 , #11038 ).
o A workaround for git being very slow on macOS has been applied,
improving performance after a fresh boot (#10535
).
New or improved bindings
o When the cursor is on a command that resolves to an executable
script, alt-o will now open that script in your editor (#10266
).
o During up-arrow history search, shift-delete will delete the current
search item and move to the next older item. Previously this was only
supported in the history pager.
o shift-delete will also remove the currently-displayed autosuggestion
from history, and remove it as a suggestion.
o ctrl-Z (also known as ctrl-shift-z) is now bound to redo.
o Some improvements to the alt-e binding which edits the command line
in an external editor: - The editor's cursor position is copied back
to fish. This is currently supported for Vim and Kakoune. - Cursor
position synchronization is only supported for a set of known
editors, which are now also detected in aliases which use complete
--wraps. For example, use complete --wraps my-vim vim to synchronize
cursors when EDITOR=my-vim. - Multiline commands are indented before
being sent to the editor, which matches how they are displayed in
fish.
o The ...-path-component bindings, like backward-kill-path-component,
now treat # as part of a path component (#10271
).
o Bindings like alt-l that print output in between prompts now work
correctly with multiline commandlines.
o alt-d on an empty command line lists the directory history again.
This restores the behavior of version 2.1.
o history-prefix-search-backward and -forward now maintain the cursor
position, instead of moving the cursor to the end of the command line
(#10430 ).
o The following keys have refined behavior if the terminal supports the
new keyboard encodings: - shift-enter now inserts a newline instead
of executing the command line. - ctrl-backspace now deletes the last
word instead of only one character (#10741 ). - ctrl-delete deletes the next word
(same as alt-d).
o New special input functions: - forward-char-passive and
backward-char-passive are like their non-passive variants but do not
accept autosuggestions or move focus in the completion pager (#10398
). -
forward-token, backward-token, kill-token, and backward-kill-token
are similar to the *-bigword variants but for the whole argument
token (which includes escaped spaces) (#2014
). -
clear-commandline, which merely clears the command line, as an
alternative to cancel-commandline which prints ^C and a new prompt
(#10213 ).
o The accept-autosuggestion special input function now returns false
when there was nothing to accept (#10608 ).
o Vi mode has seen some improvements but continues to suffer from the
lack of people working on it. - New default cursor shapes for insert
and replace mode. - ctrl-n in insert mode accepts autosuggestions
(#10339 ). -
Outside insert mode, the cursor will no longer be placed beyond the
last character on the commandline. - When the cursor is at the end
of the commandline, a single l will accept an autosuggestion (#10286
). - The
cursor position after pasting (p) has been corrected. - Added an
additional binding, _, for moving to the beginning of the line
(#10720 ). -
When the cursor is at the start of a line, escaping from insert mode
no longer moves the cursor to the previous line. - Added bindings
for clipboard interaction, like ",+,p and ",+,y,y. - Deleting in
visual mode now moves the cursor back, matching vi (#10394
). - The ;,
,, v, V, I, and gU bindings work in visual mode (#10601
, #10648
). - Support
% motion (#10593 ). - ctrl-k to remove the contents of the line
beyond the cursor in all modes (#10648 ). - Support ab and ib vi text
objects. New input functions are introduced
jump-{to,till}-matching-bracket (#1842 ). - The E binding now correctly
handles the last character of the word, by jumping to the next word
(#9700 ).
Completions
o Command-specific tab completions may now offer results whose first
character is a period. For example, it is now possible to
tab-complete git add for files with leading periods. The default file
completions hide these files, unless the token itself has a leading
period (#3707 ).
o Option completion now uses fuzzy subsequence filtering, just like
non-option completion (#830 ). This means that --fb may be completed to
--foobar if there is no better match.
o Completions that insert an entire token now use quotes instead of
backslashes to escape special characters (#5433
).
o Normally, file name completions start after the last : or = in a
token. This helps commands like rsync --files-from=. This special
meaning can now disabled by escaping these separators as \: and \=.
This matches Bash's behavior. Note that this escaping is usually not
necessary since the completion engine already tries to guess whether
the separator is actually part of a file name.
o Various new completion scripts and numerous updates to existing ones.
o Completions could hang if the PAGER environment variable was sent to
certain editors on macOS, FreeBSD and some other platforms. This has
been fixed (#10820 ).
o Generated completions are now stored in $XDG_CACHE_HOME/fish or
~/.cache/fish by default (#10369 )
o A regression in fish 3.1, where completing a command line could
change it completely, has been fixed (#10904
).
Improved terminal support
o fish now marks the prompt and command-output regions (via OSC 133) to
enable terminal shell integration (#10352 ). Shell integration shortcuts can
scroll to the next/previous prompt or show the last command output in
a pager.
o fish now reports the working directory (via OSC 7) unconditionally
instead of only for some terminals (#9955 ).
o fish now sets the terminal window title (via OSC 0) unconditionally
instead of only for some terminals (#10037 ).
o Focus reporting in tmux is no longer disabled on the first prompt.
o Focus reporting is now disabled during commands run inside key
bindings (#6942 ).
o Cursor changes are applied to all terminals that support them, and
the list of specifically-supported terminals has been removed (#10693
).
o If it cannot find the terminfo entry given by TERM environment
variable, fish will now use an included xterm-256color definition to
match the vast majority of current terminal emulators (#10905
). If you need
to have a specific terminfo profile for your terminal's TERM
variable, install it into the terminfo database.
o Further improvements to the correct display of prompts which fill the
width of the terminal (#8164 ).
Other improvements
o status gained a buildinfo subcommand, to print information on how
fish was built, to help with debugging (#10896
).
o fish_indent will now collapse multiple empty lines into one (#10325
).
o fish_indent now preserves the modification time of files if there
were no changes (#10624 ).
o Performance in launching external processes has been improved for
many cases (#10869 ).
o Performance and interactivity under Windows Subsystem for Linux has
been improved, with a workaround for Windows-specific locations being
appended to $PATH by default (#10506 ).
o On macOS, paths from /etc/paths and /etc/manpaths containing colons
are handled correctly (#10684 ).
o Additional filesystems such as AFS are properly detected as remote,
which avoids certain hangs due to expensive filesystem locks (#10818
).
o A spurious error when launching multiple instances of fish for the
first time has been removed (#10813 ).
For distributors
fish has been ported to Rust. This means a significant change in
dependencies, which are listed in the README. In short, Rust 1.70 or
greater is required, and a C++ compiler is no longer needed (although a
C compiler is still required, for some C glue code and the tests).
CMake remains the recommended build system, because of cargo's limited
support for installing support files. Version 3.5 remains the minimum
supported version. The Xcode generator for CMake is not supported any
longer (#9924 ).
CMake builds default to optimized release builds (#10799
).
fish no longer depends on the ncurses library, but still uses a
terminfo database. When packaging fish, please add a dependency on the
package containing your terminfo database instead of curses.
The test target was removed as it can no longer be defined in new CMake
versions. Use make fish_run_tests. Any existing test target will not
print output if it fails (#11116 ).
The Web-based configuration has been rewritten to use Alpine.js (#9554
).
----
fish 4.0b1 (released December 17, 2024)
A number of improvements were included in fish 4.0.0 following the beta
release of 4.0b1. These include fixes for regressions, improvements to
completions and documentation, and the removal of a small number of
problematic changes.
The full list of fixed issues can be found on the GitHub milestone page
for 4.0-final .
----
fish 3.7.1 (released March 19, 2024)
This release of fish fixes the following problems identified in fish
3.7.0:
o Deleting the last history entry via history delete works again
(#10190 ).
o Wildcards (*) will no longer sometimes generate paths that did not
exist (#10205 ).
This release also contains some improvements:
o A crash when trying to run an ELF program with a missing interpreter
has been fixed. This crashed in the process after fork, so did not
affect the fish process that tried to start the program (#10199
).
o funced will now always source the file after it has written it, even
if the contents did not change. This prevents issues if the file was
otherwise modified (#10318 ).
o The warning for when a builtin returns a negative exit code was
improved, now mentioning the original status (#10187
).
o Added completions for
o cobra-cli (#10293 )
o dmidecode (#10368 )
o mycli (#10309 )
o ollama (#10327 )
o pstree (#10317 )
o Some improvements to documentation and completions.
----
fish 3.7.0 (released January 1, 2024)
This release of fish includes a number of improvements over fish 3.6.4,
detailed below. Although work continues on the porting of fish
internals to the Rust programming language, that work is not included
in this release. fish 3.7.0 and any future releases in the 3.7 series
remain C++ programs.
Notable improvements and fixes
o Improvements to the history pager, including:
o The history pager will now also attempt subsequence matches (#9476
), so you can
find a command line like git log 3.6.1..Integration_3.7.0 by
searching for gitInt.
o Opening the history pager will now fill the search field with a
search string if you're already in a search (#10005
). This
makes it nicer to search something with up and then later decide to
switch to the full pager.
o Closing the history pager with enter will now copy the search text
to the commandline if there was no match, so you can continue
editing the command you tried to find right away (#9934
).
o Performance improvements for command completions and globbing, where
supported by the operating system, especially on slow filesystems
such as NFS (#9891 , #9931 , #10032 , #10052 ).
o fish can now be configured to wait a specified amount of time for a
multi-key sequence to be completed, instead of waiting indefinitely.
For example, this makes binding kj to switching modes in vi mode
possible. The timeout can be set via the new
fish_sequence_key_delay_ms variable (#7401 ), and may be set by default in future
versions.
Deprecations and removed features
o LS_COLORS is no longer set automatically by the ls function (#10080
). Users that
set .dircolors should manually import it using other means. Typically
this would be set -gx LS_COLORS (dircolors -c .dircolors | string
split ' ')[3]
Scripting improvements
o Running exit with a negative number no longer crashes fish (#9659
).
o fish --command will now return a non-zero status if parsing failed
(#9888 ).
o The jobs builtin will now escape the commands it prints (#9808
).
o string repeat no longer overflows if the count is a multiple of the
chunk size (#9900 ).
o The builtin builtin will now properly error out with invalid
arguments instead of doing nothing and returning true (#9942
).
o command time in a pipeline is allowed again, as is command and and
command or (#9985 ).
o exec will now also apply variable overrides, so FOO=bar exec will now
set $FOO correctly (#9995 ).
o umask will now handle empty symbolic modes correctly, like umask
u=,g=rwx,o= (#10177 ).
o Improved error messages for errors occurring in command substitutions
(#10054 ).
Interactive improvements
o read no longer enables bracketed paste so it doesn't stay enabled in
combined commandlines like mysql -p(read --silent) (#8285
).
o Vi mode now uses fish_cursor_external to set the cursor shape for
external commands (#4656 ).
o Opening the history search in vi mode switches to insert mode
correctly (#10141 ).
o Vi mode cursor shaping is now enabled in iTerm2 (#9698
).
o Completing commands as root includes commands not owned by root,
fixing a regression introduced in fish 3.2.0 (#9699
).
o Selection uses fish_color_selection for the foreground and background
colors, as intended, rather than just the background (#9717
).
o The completion pager will no longer sometimes skip the last entry
when moving through a long list (#9833 ).
o The interactive history delete interface now allows specifying index
ranges like "1..5" (#9736 ), and history delete --exact now properly saves
the history (#10066 ).
o Command completion will now call the stock manpath on macOS, instead
of a potential Homebrew version. This prevents awkward error messages
(#9817 ).
o the redo special input function restores the pre-undo cursor
position.
o A new bind function history-pager-delete, bound to shift-delete by
default, will delete the currently-selected history pager item from
history (#9454 ).
o fish_key_reader will now use printable characters as-is, so pressing
"o" no longer leads to it telling you to bind \u00F6 (#9986
).
o open can be used to launch terminal programs again, as an xdg-open
bug has been fixed and a workaround has been removed (#10045
).
o The repaint-mode binding will now only move the cursor if there is
repainting to be done. This fixes alt combination bindings in vi mode
(#7910 ).
o A new clear-screen bind function is used for ctrl-l by default. This
clears the screen and repaints the existing prompt at first, so it
eliminates visible flicker unless the terminal is very slow (#10044
).
o The alias convenience function has better support for commands with
unusual characters, like + (#8720 ).
o A longstanding issue where items in the pager would sometimes display
without proper formatting has been fixed (#9617
).
o The alt-l binding, which lists the directory of the token under the
cursor, correctly expands tilde (~) to the home directory (#9954
).
o Various fish utilities that use an external pager will now try a
selection of common pagers if the PAGER environment variable is not
set, or write the output to the screen without a pager if there is
not one available (#10074 ).
o Command-specific tab completions may now offer results whose first
character is a period. For example, it is now possible to
tab-complete git add for files with leading periods. The default file
completions hide these files, unless the token itself has a leading
period (#3707 ).
Improved prompts
o The default theme now only uses named colors, so it will track the
terminal's palette (#9913 ).
o The Dracula theme has now been synced with upstream (#9807
); use
fish_config to re-apply it to pick up the changes.
o fish_vcs_prompt now also supports fossil (#9497
).
o Prompts which display the working directory using the prompt_pwd
function correctly display directories beginning with dashes (#10169
).
Completions
o Added completions for:
o age and age-keygen (#9813 )
o airmon-ng (#10116 )
o ar (#9720 )
o blender (#9905 )
o bws (#10165 )
o calendar (#10138 )
o checkinstall (#10106 )
o crc (#10034 )
o doctl
o gimp (#9904 )
o gojq (#9740 )
o horcrux (#9922 )
o ibmcloud (#10004 )
o iwctl (#6884 )
o java_home (#9998 )
o krita (#9903 )
o oc (#10034 )
o qjs (#9723 )
o qjsc (#9731 )
o rename (#10136 )
o rpm-ostool (#9669 )
o smerge (#10135 )
o userdel (#10056 )
o watchexec (#10027 )
o wpctl (#10043 )
o xxd (#10137 )
o zabbix (#9647 )
o The zfs completions no longer print errors about setting a read-only
variable (#9705 ).
o The kitty completions have been removed in favor of keeping them
upstream (#9750 ).
o git completions now support aliases that reference other aliases
(#9992 ).
o The gw and gradlew completions are loaded properly (#10127
).
o Improvements to many other completions.
o Improvements to the manual page completion generator (#9787
, #9814
, #9961
).
Other improvements
o Improvements and corrections to the documentation.
o The Web-based configuration now uses a more readable style when
printed, such as for a keybinding reference (#9828
).
o Updates to the German translations (#9824 ).
o The colors of the Nord theme better match their official style
(#10168 ).
For distributors
o The licensing information for some of the derived code distributed
with fish was incomplete. Though the license information was present
in the source distribution, it was not present in the documentation.
This has been corrected (#10162 ).
o The CMake configure step will now also look for libterminfo as an
alternative name for libtinfo, as used in NetBSD curses (#9794
).
----
fish 3.6.4 (released December 5, 2023)
This release contains a complete fix for the test suite failure in fish
3.6.2 and 3.6.3.
----
fish 3.6.3 (released December 4, 2023)
This release contains a fix for a test suite failure in fish 3.6.2.
----
fish 3.6.2 (released December 4, 2023)
This release of fish contains a security fix for CVE-2023-49284, a
minor security problem identified in fish 3.6.1 and previous versions
(thought to affect all released versions of fish).
fish uses certain Unicode non-characters internally for marking
wildcards and expansions. It incorrectly allowed these markers to be
read on command substitution output, rather than transforming them into
a safe internal representation.
For example, echo \UFDD2HOME has the same output as echo $HOME.
While this may cause unexpected behavior with direct input, this may
become a minor security problem if the output is being fed from an
external program into a command substitution where this output may not
be expected.
----
fish 3.6.1 (released March 25, 2023)
This release of fish contains a number of fixes for problems identified
in fish 3.6.1, as well as some enhancements.
Notable improvements and fixes
o abbr --erase now also erases the universal variables used by the old
abbr function. That means:
abbr --erase (abbr --list)
can now be used to clean out all old abbreviations (#9468
).
o abbr --add --universal now warns about --universal being
non-functional, to make it easier to detect old-style abbr calls
(#9475 ).
Deprecations and removed features
o The Web-based configuration for abbreviations has been removed, as it
was not functional with the changes abbreviations introduced in 3.6.0
(#9460 ).
Scripting improvements
o abbr --list no longer escapes the abbr name, which is necessary to be
able to pass it to abbr --erase (#9470 ).
o read will now print an error if told to set a read-only variable,
instead of silently doing nothing (#9346 ).
o set_color -v no longer crashes fish (#9640 ).
Interactive improvements
o Using fish_vi_key_bindings in combination with fish's --no-config
mode works without locking up the shell (#9443