/** \mainpage Fish user documentation \section toc Table of contents - Fish user documentation @toc@ \section introduction Introduction This is the documentation for \c fish, the friendly interactive shell. \c fish is a user friendly commandline shell intended mostly for interactive use. A shell is a program used to execute other programs. For the latest information on \c fish, please visit the fish homepage. \section syntax Syntax overview Shells like fish are used by giving them commands. Every \c fish command follows the same simple syntax. A command is executed by writing the name of the command followed by any arguments. Example: echo hello world calls the \c echo command. \c echo is a command which will write its arguments to the screen. In the example above, the output will be 'hello world'. Everything in fish is done with commands. There are commands for performing a set of commands multiple times, commands for assigning variables, commands for treating a group of commands as a single command, etc.. And every single command follows the same simple syntax. If you want to find out more about the echo command used above, read the manual page for the echo command by writing: man echo \c man is a command for displaying a manual page on a given topic. The man command takes the name of the manual page to display as an argument. There are manual pages for almost every command on most computers. There are also manual pages for many other things, such as system libraries and important files. Every program on your computer can be used as a command in \c fish. If the program file is located in one of the directories in the PATH, it is sufficient to type the name of the program to use it. Otherwise the whole filename, including the directory (like \c /home/me/code/checkers/checkers or \c ../checkers) has to be used. Here is a list of some useful commands: - \c cd, change the current directory - \c ls, list files and directories - \c man, display a manual page on the screen - \c mv, move (rename) files - \c cp, copy files - \c open, open files with the default application associated with each filetype - \c less, list the contents of files Commands and parameters are separated by the space character ( ). Every command ends with either a newline (i.e. by pressing the return key) or a semicolon (;). More than one command 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 \c ls command usually lists all the files and directories in the current working directory, but by using the \c -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 documented in the manual page for each command. Some switches are common to most command though, for example '--help' will usually display a help text, '-i' will often turn on interactive prompting before taking action, while '-f' will turn it off. \subsection quotes Quotes Sometimes features such as parameter expansion and character escapes get in the way. When that happens, the user can write a parameter within quotes, either ' (single quote) or " (double quote). There is one important difference between single quoted and double quoted strings: When using double quoted string, variable expansion still takes place. Other than that, a quoted parameter will not be parameter expanded, may contain spaces, and escape sequences are ignored. The only backslash escape accepted within single quotes is \\', which escapes a single quote and \\\\, which escapes the backslash symbol. The only backslash escapes accepted within double quotes are \\", which escapes a double quote, \\$, which escapes a dollar character, and \\\\, which escapes the backslash symbol. Single quotes have no special meaning withing double quotes and vice versa. Example: rm "cumbersome filename.txt" Will remove the file 'cumbersome filename.txt', while rm cumbersome filename.txt would remove the two files 'cumbersome' and 'filename.txt'. \subsection escapes Escaping characters Some characters can not be written directly on the command line. For these characters, so called escape sequences are provided. These are: - '\\a', escapes the alert character - '\\b', escapes the backspace character - '\\e', escapes the escape character - '\\f', escapes the form feed character - '\\n', escapes a newline character - '\\r', escapes the carriage return character - '\\t', escapes the tab character - '\\v', escapes the vertical tab character - '\\ ', escapes the space character - '\\$', escapes the dollar character - '\\\\', escapes the backslash character - '\\*', escapes the star character - '\\?', escapes the question mark character - '\\~', escapes the tilde character - '\\%%', escapes the percent character - '\\#', escapes the hash character - '\\(', escapes the left parenthesis character - '\\)', escapes the right parenthesis character - '\\{', escapes the left curly bracket character - '\\}', escapes the right curly bracket character - '\\[', escapes the left bracket character - '\\]', escapes the right bracket character - '\\\<', escapes the less than character - '\\\>', escapes the more than character - '\\^', escapes the circumflex character - '\\&', escapes the ampersand character - '\\;', escapes the semicolon character - '\\"', escapes the quote character - '\\'', escapes the apostrophe character - '\\xxx', where xx is a hexadecimal number, escapes the ascii character with the specified value. For example, \\x9 is the tab character. - '\\Xxx', where xx is a hexadecimal number, escapes a byte of data with the specified value. If you are using a mutibyte encoding, this can be used to enter invalid strings. Only use this if you know what you are doing. - '\\ooo', where ooo is an octal number, escapes the ascii character with the specified value. For example, \\011 is the tab character. - '\\uxxxx', where xxxx is a hexadecimal number, escapes the 16-bit Unicode character with the specified value. For example, \\u9 is the tab character. - '\\Uxxxxxxxx', where xxxxxxxx is a hexadecimal number, escapes the 32-bit Unicode character with the specified value. For example, \\U9 is the tab character. - '\\cx', where x is a letter of the alphabet, escapes the control sequence generated by pressing the control key and the specified letter. For example, \\ci is the tab character \subsection redirects IO redirection Most program use three types of input/output (IO), each represented by a number called a file descriptor (FD). These are: - Standard input, FD 0, for reading, defaults to reading from the keyboard. - Standard output, FD 1, for writing, defaults to writing to the screen. - Standard error, FD 2, for writing errors and warnings, defaults to writing to the screen. The reason for providing for two output file descriptors is to allow separation of errors and warnings from regular program output. Any file descriptor can be directed to a different output than its default through a simple mechanism called a redirection. An example of a file redirection is echo hello \>output.txt, which directs the output of the echo command to the file error.txt. - To redirect standard input, write \ - To redirect standard output, write \>DESTINATION - To redirect standard error, write ^DESTINATION - To redirect standard output to a file which will be appended, write \>\>DESTINATION_FILE - To redirect standard error to a file which will be appended, write ^^DESTINATION_FILE DESTINATION can be one of the following: - A filename. The output will be written to the specified file. - An ampersand (\&) followed by the number of another file descriptor. The file descriptor will be a duplicate of the specified file descriptor. - An ampersand followed by a minus sign (\&-). The file descriptor will be closed. Example: To redirect both standard output and standard error to the file all_output.txt, you can write echo Hello \>all_output.txt ^\&1. Any FD can be redirected in an arbitrary way by prefixing the redirection with the number of the FD. - To redirect input of FD number N, write N\ - To redirect output of FD number N, write N\>DESTINATION - To redirect output of FD number N to a file which will be appended, write N\>\>DESTINATION_FILE Example: echo Hello 2\>- and echo Hello ^- are equivalent. \subsection piping Piping The user can string together multiple commands into a so called pipeline. This means that the standard output of one command will be read in as standard input into the next command. This is done by separating the commands by the pipe character (|). For example cat foo.txt | head will call the 'cat' program with the parameter 'foo.txt', which will print the contents of the file 'foo.txt'. The contents of foo.txt will then be filtered through the program 'head', which will pass on the first ten lines of the file to the screen. For more information on how to combine commands through pipes, read the manual pages of the commands you want to use using the 'man' command. If you want to find out more about the 'cat' program, type man cat. Pipes usually connect file descriptor 1 (standard output) of the first process to file descriptor 0 (standard input) of the second process. It is possible use a different output file descriptor by prepending the desired FD number and then output redirect symbol to the pipe. For example: make fish 2>|less will attempt to build the fish program, and any errors will be shown using the less pager. \subsection syntax-background Background jobs When you start a job in \c fish, \c 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 a \& (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. \subsection syntax-job-control Job control Most programs allow you to suspend the programs execution and return control to \c fish by Pressing ^Z (Press and hold the Control key and press 'z'). Once back at the \c fish commandline, you can start other programs and do anything you want. If you then want to go back to the suspended command by using the fg 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. \subsection syntax-function Shellscript functions Functions are used to group together commands and arguments using a single name. It can also be used to start a specific command with additional arguments. For example, the following is a function definition that calls the command 'ls -l' to print a detailed listing of the contents of the current directory:
function ll
	ls -l $argv
end
The first line tells fish that a function by the name of ll is to be defined. To use it, simply write ll on the commandline. The second line tells fish that the command ls -l $argv should be called when ll is invoked. $argv is an array variable, which always contains all arguments sent to the function. In the example above, these are simply passed on to the ls command. For more information on functions, see the documentation for the function builtin. \subsubsection syntax-function-wrappers Defining wrapper functions One of the most common used for functions is to slightly alter the behavior of an already existing command. For example, one might want to redefine the \c ls command to display colors. The switch for turning on colors on GNU systems is \c '--color=auto'. A wrapper around \c ls might look like this:
function ls
	ls --color=auto $argv
end
There are a few important things that need to be noted about wrapper functions: - Wrappers should 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. - If the wrapped command is not the first command to be called by the wrapper, it is necessary to prefix the call to the command with the word 'command' in order to tell fish that the function should not call itself, but rather a command with the same name. Failing to do so will cause infinite recursion bugs. \subsubsection syntax-function-autoloading Autoloading functions Functions can be defined on the commandline or in a configuration file, but they can also be automatically loaded. This method of defining functions has several advantages. An autoloaded function becomes available automatically to all running shells, if the function definition is changed, all running shells will automatically reload the altered version, startup time and memory usage is improved, etc. Fish automatically searches through any directories in the array variable \$fish_function_path, and any functions defined are automatically loaded when needed. A function definition file must have a filename consisting of the name of the function plus the suffix '.fish'. The default value for \$fish_function_path is \c ~/.config/fish/functions \c /etc/fish/functions \c /usr/share/fish/functions. The exact path to the last two of these may be slightly different depending on what install path prefix was chosen at configuration time. The rationale behind having three different directories is that the first one is for user specific functions, the second one is for system-wide additional functions and the last one is for default fish functions. The path list is searched in order, meaning that by default, the system administrator can override default fish functions, and the user can override functions defined by the system administrator. It is very important that function definition files only contain the definition for the specified function and nothing else, otherwise it is possible that autoloading a function files requires that the function already be loaded, i.e. a circular dependency. \subsection syntax-conditional Conditional execution of code There are four fish builtins that let you execute commands only if a specific criterion is met. These builtins are if, switch, and and or. The \c switch command is used to execute one of possibly many blocks of commands depending on the value of a string. See the documentation for switch for more information. The other conditionals use the exit status of a command to decide if a command or a block of commands should be executed. See the documentation for if, and and or for more information. \subsection syntax-words Some common words This is a short explanation of some of the commonly used words in fish. - argument, a parameter given to a command - builtin, a command that is implemented in the shell. Builtins are commands that are so closely tied to the shell that it is impossible to implement them as external commands. - command, a program that the shell can run. - function, a block of commands that can be called as if they where a single command. By using functions, it is possible to string together multiple smaller commands into one more advanced command. - job, a running pipeline or command - pipeline, a set of commands stringed together so that the output of one command is the input of the next command - redirection, a operation that changes one of the input/output streams associated with a job - switch, a special flag sent as an argument to a command that will alter the behavior of the command. A switch almost always begins with one or two hyphens. \section help Help \c 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. Help on a specific builtin can also be obtained with the -h parameter. For instance, to obtain help on the \c fg builtin, either type fg -h or help fg. \section completion Tab completion Tab completion is one of the most time saving features of any modern shell. By tapping the tab key, the user asks \c fish to guess the rest of the command or parameter that the user is currently typing. If \c fish can only find one possible completion, \c fish will write it out. If there is more than one completion, \c fish will write out the longest prefix that all completions have in common. If the completions differ on the first character, a list of all possible completions is printed. The list features descriptions of the completions and if the list doesn't fit the screen, it is scrollable by using the arrow keys, the page up/page down keys, the tab key or the space bar. Pressing any other key will exit the list and insert the pressed key into the command line. These are the general purpose tab completions that \c fish provides: - Completion of commands, both builtins, functions and regular programs. - Completion of environment variable names. - Completion of usernames for tilde expansion. - Completion of filenames, even on strings with wildcards such as '*', '**' and '?'. - Completion of job id, job name and process names for process expansion. \c fish provides a large number of program specific completions. Most of these completions are simple options like the \c -l option for \c ls, but some are more advanced. The latter include: - The programs 'man' and 'whatis' show all installed manual pages as completions. - The 'make' program uses all targets in the Makefile in the current directory as completions. - The 'mount' command uses all mount points specified in fstab as completions. - The 'ssh' command uses all hosts that are stored in the known_hosts file as completions. (see the ssh documentation for more information) - The 'su' command uses all users on the system as completions. - The \c apt-get, \c rpm and \c yum commands use all installed packages as completions. \subsection completion-own Writing your own completions Specifying your own completions is not difficult. To specify a completion, use the \c complete command. \c complete takes as a parameter the name of the command to specify a completion for. For example, to add a completion for the program \c myprog, one would start the completion command with complete -c myprog .... To provide a list of possible completions for myprog, use the \c -a switch. If \c myprog accepts the arguments start and stop, this can be specified as complete -c myprog -a 'start stop'. The argument to the \c -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. Fish has a special syntax to support specifying switches accepted by a command. The switches \c -s, \c -l and \c -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 (like -shuffle), respectively. If the command 'myprog' has an option '-o' which can also be written as '--output', and which can take an additional value of either 'yes' or 'no', this can be specified by writing: complete -c myprog -s o -l output -a "yes no" There are also special switches for specifying that a switch requires an argument, to disable filename completion, to create completions that are only available in some combinations, etc.. For a complete description of the various switches accepted by the \c complete command, see the documentation for the complete builtin, or write 'complete --help' inside the \c fish shell. 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) \subsection completion-func Useful functions for writing completions Fish ships with several functions that are very useful when writing command specific completions. Most of these functions name begins with the string '__fish_'. Such functions are internal to fish and their name and interface may change in future fish versions. Still, some of them may be very useful when writing completions. A few of these functions are described here. Be aware that they may be removed or changed in future versions of fish. 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.
__fish_complete_directories STRING DESCRIPTION
performs path completion on STRING, allowing only directories, and giving them the description DESCRIPTION.
__fish_complete_groups
prints a list of all user groups with the groups members as description.
__fish_complete_pids
prints a list of all processes IDs with the command name as description.
__fish_complete_suffix SUFFIX
performs file completion allowing only files ending in SUFFIX. The mimetype database is used to find a suitable description.
__fish_complete_users
prints a list of all users with their full name as description.
__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.
__fish_print_hostnames
prints a list of all known hostnames. This functions searches the fstab for nfs servers, ssh for known hosts and checks the /etc/hosts file.
__fish_print_interfaces
prints a list of all known network interfaces.
__fish_print_packages
prints a list of all installed packages. This function currently handles Debian, rpm and Gentoo packages. \subsection completion-path 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 array 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'. The default value for \$fish_complete_path is ~/.config/fish/completions, /etc/fish/completions and /usr/share/fish/completions. The exact path to the last two of these may be slightly different depending on what install path prefix was chosen at configuration time. If a suitable file is found in one of these directories, it will be automatically loaded and the search will be stopped. The rationale behind having three different directories is that the first one is for user specific completions, the second one is for system-wide completions and the last one is for default fish completions. If you have written new completions for a common Unix command, please consider sharing your work by sending it to the fish mailing list. \section expand Parameter expansion (Globbing) When an argument for a program is given on the commandline, it undergoes the process of parameter expansion before it is sent on to the command. Parameter expansion is a powerful set of mechanisms that allow you to expand the parameter in various ways, including performing wildcard matching on files, inserting the value of environment variables into the parameter or even using the output of another command as a parameter list. \subsection expand-wildcard Wildcards If a star (*) or a question mark (?) is present in the parameter, \c fish attempts to match the given parameter to any files in such a way that: - '?' can match any single character except '/'. - '*' can match any string of characters not containing '/'. This includes matching an empty string. - '**' matches any string of characters. This includes matching an empty string. The string may include the '/' character but does not need to. Wildcard matches are sorted case insensitively. When sorting matches containing numbers, consecutive digits are considered to be one element, so that the strings '1' '5' and '12' would be sorted in the order given. File names beginning with a dot are not considered when wildcarding unless a dot is specifically given as the first character of the file name. Examples: a* matches any files beginning with an 'a' in the current directory. ??? matches any file in the current directory whose name is exactly three characters long. ** matches any files and directories in the current directory and all of its subdirectories. If no matches are found for a specific wildcard, it will expand into zero arguments, i.e. to nothing. If none of the wildcarded arguments sent to a command result in any matches, the command will not be executed. If this happens when using the shell interactively, a warning will also be printed. \subsection expand-command-substitution Command substitution If a parameter contains a set of parenthesis, the text enclosed by the parenthesis will be interpreted as a list of commands. On expansion, this list is executed, and substituted by the output. If the output is more than one line long, each line will be expanded to a new parameter. A command substitution will not change the value of the status variable outside of the command substitution. Example: The command echo (basename image.jpg .jpg).png will output 'image.png'. The command for i in *.jpg; convert $i (basename $i .jpg).png; end will convert all Jpeg files in the current directory to the PNG format. \subsection expand-brace Brace expansion A comma separated list of characters enclosed in curly braces will be expanded so each element of the list becomes a new parameter. Example: echo input.{c,h,txt} outputs 'input.c input.h input.txt' The command mv *.{c,h} src/ moves all files with the suffix '.c' or '.h' to the subdirectory src. \subsection expand-variable Variable expansion A dollar sign followed by a string of characters is expanded into the value of the environment variable with the same name. For an introduction to the concept of environment variables, read the Environment variables section. Example: echo \$HOME prints the home directory of the current user. If you wish to combine environment variables with text, you can encase the variables within braces to embed a variable inside running text like echo Konnichiwa {$USER}san, which will print a personalized Japanese greeting. The {$USER}san syntax might need a bit of an elaboration. Posix shells allow you to specify a variable name using '$VARNAME' or '${VARNAME}'. Fish supports the former, and has no support whatsoever for the latter or anything like it. So what is '{$VARNAME}' then? Well, '{WHATEVER}' is brace expansion, e.g. 'a{b,c}d' -> 'abd acd'. So '{$VARNAME}' is a bracket-expansion with only a single element, i.e. it becomes expanded to '$VARNAME', which will be variable expanded to the value of the variable 'VARNAME'. So you might think that the brackets don't actually do anything, and that is nearly the truth. The snag is that there once along the way was a '}' in there somewhere, and } is not a valid character in a variable name. So anything after the otherwise pointless bracket expansion becomes explicitly NOT a part of the variable name, even if it happens to be a legal variable name character. That's why '{$USER}san' looks for the variable '$USER' and not for the variable '$USERsan'. It's simply a case of one syntax lending itself nicely to solving an unrelated problem in its spare time. Variable expansion is the only type of expansion performed on double quoted strings. There is, however, an important difference in how variables are expanded when quoted and when unquoted. An unquoted variable expansion will result in a variable number of arguments. For example, if the variable $foo has zero elements or is undefined, the argument $foo will expand to zero elements. If the variable $foo is an array of five elements, the argument $foo will expand to five elements. When quoted, like "$foo", a variable expansion will always result in exactly one argument. Undefined variables will expand to the empty string, and array variables will be concatenated using the space character. There is one further notable feature of fish variable expansion. Consider the following code snippet:
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
The above code demonstrates how to use multiple '$' symbols to expand the value of a variable as a variable name. One can think of the $-symbol as a variable dereference operator. When using this feature together with array brackets, the brackets will always match the innermost $ dereference. Thus, $$foo[5] will always mean the fifth element of the foo variable should be dereferenced and never that the fifth element of the doubly dereferenced variable foo. The latter can instead be expressed as $$foo[1][5]. \subsection expand-home 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. \subsection expand-process Process expansion The \% (percent) character at the beginning of a parameter followed by a string is expanded into a process id. The following expansions are performed: - If the string is the entire word \c self, the shells pid is the result. - Otherwise, if the string is the id of a job, the result is the process group id of the job. - Otherwise, if any child processes match the specified string, their pids are the result of the expansion. - Otherwise, if any processes owned by the user match the specified string, their pids are the result of the expansion. This form of expansion is useful for commands like kill and fg, which take the process ids as an argument. Example: fg \%ema will search for a process whose command line begins with the letters 'ema', such as emacs, and if found, put it in the foreground. kill -s SIGINT \%3 will send the SIGINT signal to the job with job id 3. \subsection combine 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: - Command substitutions - Variable expansions - Bracket expansion - Pid expansion - Wildcard expansion Expansions are performed from right to left, nested bracket expansions 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'. \section variables Environment variables The concept of environment variables are central to any shell. Environment variables are variables, whose values can be set and used by the user. For information on how to use the current value of a variable, see the section on variable expansion. To set a variable value, use the \c set command. Example: To set the variable \c smurf_color to the value \c 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: To use the value of the variable \c smurf, write $ (dollar symbol) followed by the name of the variable, like echo Smurfs are usually $smurf_color, which would print the result 'Smurfs are usually blue'. \subsection variables-scope Variable scope There are three kinds of variables in fish, universal, global and local variables. Universal variables are shared between all fish sessions a user is running on one computer. Global variables are specific to the current fish session, but are not associated with any specific block scope, and will never be erased unless the user explicitly requests it using set -e. Local variables are specific to the current fish session, and associated with a specific block of commands, and is 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 \c 'for, \c 'while' , \c 'if', \c 'function', \c 'begin' or \c 'switch', and ends with the command \c 'end'. The user can specify that a variable should have either global or local scope using the \c -g/--global or \c -l/--local switches. Variables can be explicitly set to be universal with the \c -U or \c --universal switch, global with the \c -g or \c --global switch, or local with the \c -l or \c --local switch. The scoping rules when creating or updating a variable are: -# If a variable is explicitly set to either universal, global or local, that setting will be honored. If a variable of the same name exists in a different scope, that variable will not be changed. -# If a variable is not explicitly set to be either universal, global or local, but has been previously defined, the variable scope is not changed. -# If a variable is not explicitly set to be either universal, global or local and has never before been defined, the variable will be local to the currently executing functions. If no function is executing, the variable will be global. There may be many variables with the same name, but different scopes. When using a variable, the variable scope will be searched from the inside out, i.e. a local variable will be used rather than a global variable with the same name, a global variable will be used rather than a universal variable with the same name. Example: The following code will not output anything:
begin
	# This is a nice local scope where all variables will die
	set -l pirate 'There be treasure in them thar hills'
end

# This will not output anything, since the pirate was local
echo $pirate
\subsection variables-universal More on universal variables Universal variables are variables that are shared between all the users 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 \c 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. \subsection variables-functions Variable scope for functions When calling a function, all non-global variables temporarily disappear. This shadowing of the local scope is needed since the variable namespace would become cluttered, making it very easy to accidentally overwrite variables from another function. For example, the following code will output 'Avast, mateys':
function shiver
	set phrase 'Shiver me timbers'
end

function avast
	set phrase 'Avast, mateys'

	# Calling the shiver function here can not change any variables
	# in the local scope
	shiver

	echo $phrase
end

avast
\subsection variables-export Exporting variables Variables in fish can be exported. This means the variable will be inherited by any commands started by fish. It is convention that exported variables are in uppercase and unexported variables are in lowercase. Variables can be explicitly set to be exported with the \c -x or \c --export switch, or not exported with the \c -u or \c --unexport switch. The exporting rules when creating or updating a variable are identical to the scoping rules for variables: -# If a variable is explicitly set to either be exported or not exported, that setting will be honored. -# 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. -# If a variable is not explicitly set to be either exported or not exported and has never before been defined, the variable will not be exported. \subsection variables-arrays Arrays \c fish can store a list of multiple strings inside of a variable. To access one element of an array, use the index of the element inside of square brackets, like this:
echo $PATH[3]
Note that array indices start at 1 in fish, not 0, as is more common in other languages. This is because many common Unix tools like seq are more suited to such use. If you do not use any brackets, all the elements of the array will be written as separate items. This means you can easily iterate over an array using this syntax:
for i in $PATH; echo $i is in the path; end
To create a variable \c smurf, containing the items \c blue and \c small, simply write:
set smurf blue small
It is also possible to set or erase individual elements of an array:
\#Set smurf to be an array 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 an array variable, the index will be calculated from the end of the array. For example, the index -1 means the last index of an array. \subsection variables-special Special variables The user can change the settings of \c fish by changing the values of certain environment variables. - \c BROWSER, which is the users 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. - \c CDPATH, which is an array of directories in which to search for the new directory for the \c cd builtin. The fish init files defined CDPATH to be a universal variable with the values . and ~. - A large number of variable starting with the prefixes \c fish_color and \c fish_pager_color. See Variables for changing highlighting colors for more information. - \c fish_greeting, which is the greeting message printed on startup. - \c LANG, \c LC_ALL, \c LC_COLLATE, \c LC_CTYPE, \c LC_MESSAGES, \c LC_MONETARY, \c LC_NUMERIC and \c LC_TIME set the language option for the shell and subprograms. See the section Locale variables for more information. - \c PATH, which is an array of directories in which to search for commands - \c umask, which is the current file creation mask. The preferred way to change the umask variable is through the umask shellscript function. An attempt to set umask to an invalid value will always fail. \c fish also sends additional information to the user through the values of certain environment variables. The user can not change the values of most of these variables. - \c _, which is the name of the currently running command. - \c argv, which is an array of arguments to the shell or function. \c 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 by the user. - \c history, which is an array containing the last commands that where entered. - \c HOME, which is the users home directory. This variable can only be changed by the root user. - \c PWD, which is the current working directory. - \c status, which is 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. - \c USER, which is the username. This variable can only be changed by the root user. The names of these variables are mostly derived from the csh family of shells and differ from the ones used by Bourne style shells such as bash. The csh names where chosen because Bourne style names, such as ?, * and @ lead to significantly less readable code, and much larger discoverability problems, and given the existence of tab completion, the keystroke savings are minimal. Variables whose name are in uppercase are exported to the commands started by fish, those in lowercase are not exported. This rule is not enforced by fish, but it is good coding practice to use casing to distinguish between exported and unexported variables. \c fish also uses several variables internally. Such variables are prefixed with the string __FISH or __fish. These should never be used by the user. Changing their value may break fish. \subsection variables-status 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 \c status variable. If fish encounters a problem while executing a command, the status variable may also be set to a specific value: - 1 is the generally the exit status from fish builtins if they where supplied with invalid arguments - 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. \subsection variables-color Variables for changing highlighting colors The colors used by fish for syntax highlighting can be configured by changing the values of a various variables. The value of these variables can be one of the colors accepted by the set_color command. The \c --bold or \c -b switches accepted by \c set_color are also accepted. The following variables are available to change the highlighting colors in fish: - \c fish_color_normal, the default color - \c fish_color_command, the color for commands - \c fish_color_quote, the color for quoted blocks of text - \c fish_color_redirection, the color for IO redirections - \c fish_color_end, the color for process separators like ';' and '&' - \c fish_color_error, the color used to highlight potential errors - \c fish_color_param, the color for regular command parameters - \c fish_color_comment, the color used for code comments - \c fish_color_match, the color used to highlight matching parenthesis - \c fish_color_search_match, the color used to highlight history search matches - \c fish_color_operator, the color for parameter expansion operators like '*' and '~' - \c fish_color_escape, the color used to highlight character escapes like '\\n' and '\\x70' - \c fish_color_cwd, the color used for the current working directory in the default prompt Additionally, the following variables are available to change the highlighting in the completion pager: - \c fish_pager_color_prefix, the color of the prefix string, i.e. the string that is to be completed - \c fish_pager_color_completion, the color of the completion itself - \c fish_pager_color_description, the color of the completion description - \c fish_pager_color_progress, the color of the progress bar at the bottom left corner Example: To make errors highlighted and red, use: set fish_color_error red --bold \subsection variables-locale Locale variables The most common way to set the locale to use a command like 'set -x LANG en_GB.utf8', which sets the current locale to be the English language, as used in Great Britain, using the UTF-8 character set. For a list of available locales, use 'locale -a'. \c LANG, \c LC_ALL, \c LC_COLLATE, \c LC_CTYPE, \c LC_MESSAGES, \c LC_MONETARY, \c LC_NUMERIC and LC_TIME set the language option for the shell and subprograms. These variables work as follows: \c LC_ALL forces all the aspects of the locale to the specified value. If LC_ALL is set, all other locale variables will be ignored. The other LC_ variables set the specified aspect of the locale information. LANG is a fallback value, it will be used if none of the LC_ variables are specified. \section builtin-overview Builtins Many other shells have a large library of builtin commands. Most of these commands are also available as standalone commands, but have been implemented in the shell anyway for whatever reason. To avoid code duplication, and to avoid the confusion of subtly differing versions of the same command, \c fish only implements builtins for actions which cannot be performed by a regular command. For a list of all builtins, functions and commands shipped with fish, see the table of contents. The documentation is also available by using the --help switch of the command. \section editor Command Line editor The \c fish editor features copy and paste, a searchable history and many editor functions that can be bound to special keyboard shortcuts. The most important keybinding is probably the tab key, which is bound to the complete function. Here are some of the commands available in the editor: - Tab completes the current token - Home or Ctrl-a moves to the beginning of the line - End or Ctrl-e moves to the end of line - Left and right moves one character left or right - Alt-left and Alt-right moves one word left or right, or moves forward/backward in the directory history if the commandline is empty - Up and down 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. - Alt-up and Alt-down 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. - Delete and backspace removes one character forwards or backwards respectively - Ctrl-c deletes entire line - Ctrl-d delete one character to the right of the cursor, unless the buffer is empty, in which case the shell will exit - Ctrl-k move contents from the cursor to the end of line to the killring - Ctrl-u move contents from the beginning of line to the cursor to the killring - Ctrl-l clear and repaint screen - Ctrl-w move previous word to the killring - Alt-d move next word to the killring - Alt-w prints a short description of the command under the cursor - 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 - 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. You can change these key bindings using the bind builtin command. - \c backward-char, moves one character to the left - \c backward-delete-char, deletes one character of input to the left of the cursor - \c backward-kill-line, move everything from the beginning of the line to the cursor to the killring - \c backward-kill-word, move the word to the left of the cursor to the killring - \c backward-word, move one word to the left - \c beginning-of-history, move to the beginning of the history - \c beginning-of-line, move to the beginning of the line - \c complete, guess the remainder of the current token - \c delete-char, delete one character to the right of the cursor - \c delete-line, delete the entire line - \c dump-functions, print a list of all key-bindings - \c end-of-history, move to the end of the history - \c end-of-line, move to the end of the line - \c explain, print a description of possible problems with the current command - \c forward-char, move one character to the right - \c forward-word, move one word to the right - \c history-search-backward, search the history for the previous match - \c history-search-forward, search the history for the next match - \c kill-line, move everything from the cursor to the end of the line to the killring - \c kill-whole-line, move the line to the killring - \c kill-word, move the next word to the killring - \c yank, insert the latest entry of the killring into the buffer - \c yank-pop, rotate to the previous entry of the killring If such a script produces output, the script needs to finish by calling 'commandline -f repaint' in order to tell fish that a repaint is in order. \subsection killring Copy and paste (Kill Ring) \c fish uses an Emacs style kill ring for copy and paste functionality. Use Ctrl-K to cut from the current cursor position to the end of the line. The string that is cut (a.k.a. killed) is inserted into a linked list of kills, called the kill ring. To paste the latest value from the kill ring use Ctrl-Y. After pasting, use Meta-Y to rotate to the previous kill. If the environment variable DISPLAY is set, \c fish will try to connect to the X-windows server specified by this variable, and use the clipboard on the X server for copying and pasting. \subsection history Searchable history After a command has been entered, it is inserted at the end of a history list. Any duplicate history items are automatically removed. By pressing the up and down keys, the user 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, a history search is also performed, but instead of searching for a complete commandline, each commandline is tokenized into separate elements just like it would be before execution, and each such token is matched against the token under the cursor when the search began. History searches can be aborted by pressing the escape key. The history is stored in the file '~/.config/fish/fish_history'. It is automatically read on startup and merged on program exit. Example: To search for previous entries containing the word 'make', type 'make' in the console and press the up key. \subsection multiline 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: - Pressing the enter key while a block of commands is unclosed, i.e. when one or more block commands such as 'for', 'begin' or 'if' do not have a corresponding 'end' command. - Pressing Alt-enter instead of pressing the enter key. - By backslash escaping a newline, i.e. by inserting a backslash (\\) character before pressing the enter key. 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. \section job-control Running multiple programs Normally when \c fish starts a program, this program will be put in the foreground, meaning it will take control of the terminal and \c fish will be stopped until the program finishes. Sometimes this is not desirable. For example, you may wish to start an application with a graphical user interface from the terminal, and then be able to continue using the shell. In such cases, there are several ways in which the user can change fish's behavior. -# By ending a command with the \& (ampersand) symbol, the user tells \c fish to put the specified command into the background. A background process will be run simultaneous with \c fish. \c fish will retain control of the terminal, so the program will not be able to read from the keyboard. -# By pressing ^Z, the user stops a currently running foreground program and returns control to \c fish. Some programs do not support this feature, or remap it to another key. Gnu emacs uses ^X z to stop running. -# By using the fg and bg builtin commands, the user can send any currently running job into the foreground or background. \section initialization Initialization files On startup, \c fish evaluates the files /usr/share/fish/config.fish (Or /usr/local/fish... if you installed fish in /usr/local), /etc/fish/config.fish (Or ~/etc/fish/... if you installed fish in your home directory) and ~/.config/fish/config.fish (Or any other directory specified by the \$XDG_CONFIG_HOME variable), in that order. The first file should not be directly edited, the second one is meant for systemwide configuration and the last one is meant for user configuration. 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. Examples: If you want to add the directory ~/linux/bin to your PATH variable when using a login shell, add the following to your ~/.config/fish/config.fish file:
if status --is-login
	set PATH $PATH ~/linux/bin
end
If you want to run a set of commands when \c fish exits, use an event handler that is triggered by the exit of the shell:
function on_exit --on-process \%self
	echo fish is now exiting
end
Universal variables are stored in the file .config/fish/fishd.HOSTNAME, where HOSTNAME is the name of your computer. Do not edit this file directly, edit them through fish scripts or by using fish interactively instead. \section other Other features \subsection color Syntax highlighting \c fish interprets the command line as it is typed and uses syntax highlighting to provide feedback to the user. The most important feedback is the detection of potential errors. By default, errors are marked red. Detected errors include: - Non existing commands. - Reading from or appending to a non existing file. - Incorrect use of output redirects - Mismatched parenthesis When the cursor is over a parenthesis or a quote, \c fish also highlights its matching quote or parenthesis. To customize the syntax highlighting, you can set the environment variables \c fish_color_normal, \c fish_color_command, \c fish_color_substitution, \c fish_color_redirection, \c fish_color_end, \c fish_color_error, \c fish_color_param, \c fish_color_comment, \c fish_color_match, \c fish_color_search_match, \c fish_color_cwd, \c fish_pager_color_prefix, \c fish_pager_color_completion, \c fish_pager_color_description and \c fish_pager_color_progress. Usually, the value of these variables will be one of \c black, \c red, \c green, \c brown, \c yellow, \c blue, \c magenta, \c purple, \c cyan, \c white or \c normal, but they can be an array containing any color options for the set_color command. Issuing set fish_color_error black --background=red --bold will make all commandline errors be written in a black, bold font, with a red background. \subsection title Programmable title When using most virtual terminals, it is possible to set the message displayed in the titlebar of the terminal window. This can be done automatically in fish by defining the \c fish_title function. The \c 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 $_ environment variable will always contain the name of the job to be put into the foreground (Or 'fish' if control is returning to the shell) when the \c fish_prompt function is called. Example:

The default \c fish title is

function fish_title
	echo $_ ' '
	pwd
end

\subsection greeting Configurable greeting If a function named fish_greeting exists after initialization, it will be run when entering interactive mode. Otherwise,if an environment variable named fish_greeting exists, it will be printed. \subsection event 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: - When a signal is delivered - When a process or job exits - When the value of a variable is updated - When the prompt is about to be shown - When a command lookup fails Example: To specify a signal handler for the WINCH signal, write:
function --on-signal WINCH my_signal_handler
	echo Got WINCH signal!
end
For more information on how to define new event handlers, see the documentation for the function command. \subsection debugging Debugging fish scripts Fish includes a built in debugger. The debugger allows you to stop execution of a script at an arbitrary point and launch a prompt. This prompt can then be used to check or change the value of any variables or perform any shellscript command. To resume normal execution of the script, simply exit the prompt. To start the debugger, simply call the builtin command 'breakpoint'. The default action of the TRAP signal is to call this builtin, so a running script can be debugged by sending it the TRAP signal. Once in the debugger, it is easy to insert new breakpoints by using the funced function to edit the definition of a function. \section issues Common issues with fish If you install fish in your home directory, fish will not work correctly for any other user than yourself. This is because fish needs its initialization files to function properly. To solve this problem, either copy the initialization files to each fish users home directory, or install them in /etc. \section i18n Translating fish to other languages Fish uses the GNU gettext library to implement translation to multiple languages. If fish is not available in your language, please consider making a translation. Currently, only the shell itself can be translated, a future version of fish should also include translated manuals. To make a translation of fish, you will first need the source code, available from the fish homepage. Download the latest version, and then extract it using a command like tar -zxf fish-VERSION.tar.gz. Next, cd into the newly created fish directory using cd fish-VERSION. You will now need to configure the source code using the command ./configure. This step might take a while. Before you continue, you will need to know the ISO 639 language code of the language you are translating to. These codes can be found here. For example, the language code for Uighur is ug. Now you have the source code and it is properly configured. Lets start translating. To do this, first create an empty translation table for the language you wish to translate to by writing make po/[LANGUAGE CODE].po in the fish terminal. For example, if you are translating to Uighur, you should write make po/ug.po. This should create the file po/ug.po, a template translation table containing all the strings that need to be translated. Now you are all set up to translate fish to a new language. Open the newly created .po file in your editor of choice, and start translating. The .po file format is rather simple. It contains pairs of string in a format like:
msgid "%ls: No suitable job\n"
msgstr ""
The first line is the English string to translate, the second line should contain your translation. For example, in Swedish the above might become:
msgid "%ls: No suitable job\n"
msgstr "%ls: Inget passande jobb\n"
\%s, \%ls, \%d and other tokens beginning with a '\%' are placeholders. These will be replaced by a value by fish at runtime. You must always take care to use exactly the same placeholders in the same order in your translation. (Actually, there are ways to avoid this, but they are too complicated for this short introduction. See the full manual for the printf C function for more information.) Once you have provided a translation for fish, please send it to fish-users@lists.sf.net. \section todo Missing features and bugs \subsection todo-features Missing features - Complete vi-mode key bindings - More completions (for example konsole, gnome-terminal, rlogin, rsync, arch, finger, bibtex, aspell, xpdf, compress, wine, dig, batch, g++, javac, java, gcj, lpr, doxygen, whois) - Undo support - wait shellscript - Support for the screen clipboard - It should be possible to test in a script if a function is autoloaded or manually defined - The validator should be better about error reporting unclosed quotes. They are usually reported as something else. \subsection todo-possible Possible features - mouse support like zsh has with http://stchaz.free.fr/mouse.zsh installed would be awesome - suggest a completion on unique matches by writing it out in an understated color - Highlight beginning/end of block when moving over a block command - command specific wildcarding (use case * instead of case '*', etc.) - Map variables. (export only the values. When expanding with no key specified, expand to all values.) - Descriptions for variables using 'set -d'. - Parse errors should when possible honor IO redirections - Support for writing strings like /u/l/b/foo and have them expand to /usr/local/bin/foo - perhaps through tab expansion - Right-side prompt - Selectable completions in the pager - Per process output redirection - Reduce the space of the pager by one line to allow the commandline to remain visible. - down-arrow could be used to save the current command to the history. Or give the next command in-sequence. Or both. - History could reload itself when the file is updated. This would need to be done in a clever way to avoid chain reactions - The error function should probably be moved into it's own library, and be made mere general purpose. - The code validation functions should be moved from the parser to parse_util. - Try to remove more malloc calls to reduce memory usage. The time_t arrays used by the autoloader sound like a good candidate. - The code validator should warn about unknown commands. - Auto-newlines - A fault injector could be written to increase robustness and testing of error recovery paths - The parser/validator could be more clever in order to make things like writing 'function --help' work as expected - Some event handler functions make much more sense as oneshots - maybe they should be automatically deleted after firing? - exec_subshell should be either merged with eval or moved to parser.c - Don't use expand_string to perform completions. wildcard_complete can be called directly, the brace expansion handling should be universal, and the process expansion can be moved to complete.c. - Make the history search support incremental searching - An automatic logout feature - Make tab completions completely silent by default, i.e. kill stderr when running completion commands. This needs to be overridalbe for debugging purposes. - Move history to an environment variable \subsection bugs Known bugs and issues - Suspending and then resuming pipelines containing a builtin or a shellscript function is broken. Ideally, the exec function in exec.c should be able to resume execution of a partially executed job. - delete-word is broken on the commandline 'sudo update-alternatives --config x-' - Sometimes autoheader needs to be run on a fresh tarball. Fix dates before creating tarballs. - The completion autoloader does not remember which completions where actually autoloaded, and may unload manually specified completions. - There have been stray reports of issues with strange values of the PATH variable during startup. - bindings in config.fish are overwritten by default key bindings. - Adding 'bind -k ...' doesn't overwrite non-keybinding binds of the same sequence. - History file does not remove duplicates. - History file should apply some kind of maximum history length. - Older versions of Doxygen has bugs in the man-page generation which cause the builtin help to render incorrectly. Version 1.2.14 is known to have this problem. If you think you have found a bug not described here, please send a report to fish-users@lists.sf.net. */