GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing fishshell.com — The fish language — fish-shell 4.9.3 documentation 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 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 Here is a list of some useful commands:
Commands and arguments are separated by the space character A switch is a very common special type of argument. Switches almost always start with one or more hyphens 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, 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:
Quotes¶Sometimes you want to give a command an argument that contains characters special to fish, like spaces or rm "my file.txt" to remove a file called fish understands two kinds of quotes: Single ( Between single quotes, fish performs no expansions. Between double quotes, fish only performs variable expansion and command substitution in the The only meaningful escape sequences in single quotes are Single quotes have no special meaning within double quotes and vice versa. More examples: grep 'enabled)$' foo.txt searches for lines ending in 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:
Some characters have special meaning to the shell. For example, an apostrophe echo \'hello world\' outputs echo 'hello world' outputs The special characters and their escape sequences are:
As a special case, Input/Output Redirection¶Most programs use three input/output (I/O) streams:
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,
As a convenience, the redirection Any arbitrary file descriptor can be used in a redirection by prefixing the redirection with the FD number.
File descriptors cannot be used with a 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*' <?myfile It is an error to redirect a builtin, function, or block to a file descriptor above 2. However this is supported for external commands. Piping¶Another way to redirect streams is a pipe. A pipe connects streams with each other. Usually the standard output of one command is connected with the standard input of another. This is done by separating commands with the pipe character cat foo.txt | head The command It is possible to pipe a different output file descriptor by prepending its FD number and the output redirect symbol to the pipe. For example: make fish 2>| less will attempt to build As a convenience, the pipe A “pager” here is a program that takes output and “paginates” it. 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:
This is important when any redirections reference other file descriptors with the Consider this helper function: # 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 it 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 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 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 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 Calling this as 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 function ls command ls --color=auto $argv end There are a few important things that need to be noted about aliases:
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 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:
When fish needs to load a function, it searches through any directories in the list variable For example if you try to execute something called By default
If you are unsure, your functions probably belong in 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 Comments¶Anything after a 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, 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
|
Symbol |
Meaning |
Example |
|---|---|---|
|
|
|
|
|
|
|
Redirection, like |
|
|
Pipe, connect two or more commands |
|
|
End of the command, instead of a newline |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
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.
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.
Global variables are specific to the current fish session. They can be erased by explicitly requesting set -e.
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.
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:
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.
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.
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
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.
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 are variables that are shared between all the user’s fish sessions on the computer. All changes to universal variables are persistent and instantly propagated across fish sessions.
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, set them once at the command line.
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.
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, 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, 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 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.
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 are a special kind of variable used to support colon-delimited path lists including PATH, CDPATH, MANPATH, PYTHONPATH, LANGUAGE (for localization) 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.
You can change the settings of fish by changing the values of certain variables.
A list of directories in which to search for commands. This is a common unix variable also used by other tools.
Locale variables such as LANG, LC_ALL, LC_MESSAGES, LC_NUMERIC and LC_TIME set the language option for the shell and subprograms.
See the section Locale variables and status language for more information.
A number of variable starting with the prefixes fish_color and fish_pager_color. See Variables for changing highlighting colors for more information.
If this is set to 0, fish will not output 24-bit RGB true-color sequences but the nearest color on the 256 color palette (or the 16 color palette, if fish_term256 is 0).
See also set_color.
The default is 1 but for historical reasons, fish defaults to behaving as if it was 0 on some terminals that are known to not support true-color sequences.
If this is set to 0 and fish_term24bit is 0, translate RGB colors down to the 16 color palette.
Also, if this is set to 0, set_color commands such as set_color ff0000 red will prefer the named color.
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.
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 defaults to 2.
controls if Autosuggestions are enabled. Set it to 0 to disable, anything else to enable. By default they are on.
If this is set to 1, fish will redraw prompts with a --final-rendering argument before running a commandline, allowing you to change it before pushing it to the scrollback. This enables transient prompts.
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.
the name of the function that sets up the keyboard shortcuts for the command-line editor.
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.
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.
determines where fish looks for completion. When trying to complete for a command, fish looks for files in the directories in this variable.
controls whether the selection is inclusive or exclusive of the character under the cursor (see Copy and Paste).
determines where fish looks for functions. When fish autoloads a function, it will look for files in these directories.
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)
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).
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.
Set it to all to also trace execution of key bindings, event handlers as well as prompt and title functions.
Controls which debug categories fish enables for output, analogous to the --debug option.
Specifies a file to direct debug output to.
a list of directories that are prepended to PATH. This can be a universal variable.
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.
if set, this string is automatically prepended to the left prompt. This is a standard environment variable that may be set by tools like systemd’s run0 to indicate special shell sessions.
if set, this string is automatically appended to the left prompt. This is a standard environment variable that may be set by tools like systemd’s run0 to indicate special shell sessions.
if set, this string is displayed when an interactive shell starts, after the greeting. This is a standard environment variable that may be set by tools like systemd’s run0 to display session information.
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).
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.
argparse sets this to the list of successfully parsed options, including option-arguments. This variable can be changed.
the runtime of the last command in milliseconds.
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.
the signal that terminated the last foreground job, or 0 if the job exited normally.
how many bytes fish will process with read or in a command substitution.
the process ID (PID) of the shell.
a read-only variable;
set to light or dark when the terminal uses a light or dark color theme respectively;
set to unknown if the terminal does not report its colors.
Like status terminal, this is only populated once the first interactive prompt is shown.
This is used in an --on-variable event handler to update syntax highlighting variables whenever the terminal’s color theme changes.
See here for how to specify light and dark variants in your theme.
a list containing the last commands that were entered.
the user’s home directory. This variable can be changed.
the machine’s hostname.
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.
the process ID (PID) of the last background process.
the current working directory.
a list of exit statuses of all processes that made up the last executed pipe. See exit status.
the level of nesting of shells. fish increments this in interactive shells, otherwise it only passes it along.
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.
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).
the current username. This variable can be changed.
the current effective user id, set by fish at startup. This variable can be changed.
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.
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:
0 is generally the exit status of commands if they successfully performed the requested operation.
1 is generally the exit status of commands if they failed to perform the requested operation.
121 is generally the exit status of commands if they were supplied with invalid arguments.
123 means that the command was not executed because the command name contained invalid characters.
124 means that the command was not executed because none of the wildcards in the command produced any matches.
125 means that while an executable with the specified name was located, the operating system could not actually execute the command.
126 means that while a file with the specified name was located, it was not executable.
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.
The “locale” of a program is its set of language and regional settings. In UNIX, these are made up of several categories. The categories used by fish are:
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 encoding part is ignored, fish always assumes UTF-8. 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.
Example values are en_US.UTF-8 for the American English or de_AT.UTF-8 for Austrian German.
Your operating system might have a locale command that you can call as locale -a to see a list of defined locales.
This is treated like LC_MESSAGES except that it can hold multiple values,
which allows to specify a priority list of languages for translation.
It’s a PATH variable, like in GNU gettext.
Language identifiers without a region specified (e.g. zh) result in all available variants of this language being tried in arbitrary order.
In this example, we might first look for messages in the zh_CN catalog, followed by zh_TW, or the other way around.
This is different from GNU gettext, which uses a “default” variant of the language instead.
If you prefer a certain variant, specify it earlier in the list,
e.g. zh_TW:zh if your preferred language is zh_TW, and you prefer any other variants of zh over the English default.
If zh_TW is the only variant of zh you want,
specifying zh_TW in the LANGUAGE variable will result in messages which are not available in zh_TW being displayed in English.
See also builtin _ (underscore).
Overrides the LANG and all other LC_* variables.
Please use LC_ALL only as a temporary override.
Determines the language in which messages are displayed, see builtin _ (underscore).
Sets the locale for formatting numbers.
fish includes a number of commands in the shell directly. We call these “builtins”. These include:
Builtins that manipulate the shell state - cd changes directory, set sets variables
Builtins for dealing with data, like string for strings and math for numbers, count for counting lines or arguments, path for dealing with path
status for asking about the shell’s status
test for checking conditions
argparse for parsing function arguments
source to read a script in the current shell (so changes to variables stay) and eval to execute a string as script
random to get random numbers or pick a random element from a list
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.
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:
It tries to resolve it as a function.
If the function is already known, it uses that
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)
If the function is now defined it uses that
It tries to resolve it as a builtin.
It tries to find an executable file in PATH.
If it finds a file, it tells the kernel to run it.
If the kernel knows how to run the file (e.g. via a #! line - #!/bin/sh or #!/usr/bin/python), it does it.
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
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 print something without asking because there are fewer than five files.
The names given to variables and functions (so-called “identifiers”) have to follow certain rules:
A variable name cannot be empty. It can contain only letters, digits, and underscores. It may begin and end with any of those characters.
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.
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).
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:
Configuration snippets (named *.fish) in the directories:
$__fish_config_dir/conf.d (by default, ~/.config/fish/conf.d/)
$__fish_sysconf_dir/conf.d (by default, /etc/fish/conf.d/)
Directories for others to ship configuration snippets for their software:
the directories under $__fish_user_data_dir (usually ~/.local/share/fish, controlled by the XDG_DATA_HOME environment variable)
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”).
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).
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.
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 mark-prompt on 4.0 write OSC 133 prompt markers to the terminal ignore-terminfo on 4.1 do not look up $TERM in terminfo database query-term on 4.1 query the TTY to enable extra functionality omit-term-workarounds off 4.3 skip workarounds for incompatible terminals
Here is what they mean:
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 be ignored. The flag made ^ an ordinary character instead of denoting an stderr redirection. Use 2> instead.
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.
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.
ampersand-nobg-in-token was introduced in fish 3.4 (and made the default in 3.5). It makes it so a & is 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.
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.
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.
mark-prompt makes fish report to the terminal the beginning and end of both shell prompts and command output.
ignore-terminfo was introduced in fish 4.1 and cannot be turned off since fish 4.5. It can still be tested for compatibility, but a no-ignore-terminfo value will be ignored. The flag disabled lookup of $TERM in the terminfo database.
query-term allows fish to query the terminal by writing escape sequences and reading the terminal’s response.
This enables features such as scrolling.
If you use an incompatible terminal, you can -- for the time being -- work around it by running (once) set -Ua fish_features no-query-term.
omit-term-workarounds prevents fish from trying to work around incompatible terminals.
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
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:
When a signal is delivered
When a job exits
When the value of a variable is updated
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:
fish_prompt is emitted whenever a new fish prompt is about to be displayed.
fish_preexec is emitted right before executing an interactive command. The commandline is passed as the first parameter. Not emitted if command is empty.
fish_posterror is emitted right after executing a command with syntax errors. The commandline is passed as the first parameter.
fish_postexec is emitted right after executing an interactive command. The commandline is passed as the first parameter. Not emitted if command is empty.
fish_exit is emitted right before fish exits.
fish_cancel is emitted when a commandline is cleared.
fish_focus_in is emitted when fish’s terminal gains focus.
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.
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, type exit or ctrl-d.
To start a debug session 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 <PID>). 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.
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.