1.. _language: 2 3The fish language 4***************** 5 6This document is a comprehensive overview of fish's scripting language. 7 8For interactive features see :ref:`Interactive use <interactive>`. 9 10.. _syntax: 11 12Syntax overview 13--------------- 14 15Shells 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:: 16 17 echo hello world 18 19This calls the :ref:`echo <cmd-echo>` command. ``echo`` writes its arguments to the screen. In this example the output is ``hello world``. 20 21Everything 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. 22 23To learn more about the ``echo`` command, read its manual page by typing ``man echo``. ``man`` is a command for displaying a manual page on a given topic. It takes the name of the manual page to display as an argument. There are manual pages for almost every command. There are also manual pages for many other things, such as system libraries and important files. 24 25Every program on your computer can be used as a command in fish. If the program file is located in one of the :ref:`PATH <PATH>` directories, you can just type the name of the program to use it. Otherwise the whole filename, including the directory (like ``/home/me/code/checkers/checkers`` or ``../checkers``) is required. 26 27Here is a list of some useful commands: 28 29- :ref:`cd <cmd-cd>`: Change the current directory 30- ``ls``: List files and directories 31- ``man``: Display a manual page 32- ``mv``: Move (rename) files 33- ``cp``: Copy files 34- :ref:`open <cmd-open>`: Open files with the default application associated with each filetype 35- ``less``: Display the contents of files 36 37Commands and arguments are separated by the space character ``' '``. Every command ends with either a newline (by pressing the return key) or a semicolon ``;``. Multiple commands can be written on the same line by separating them with semicolons. 38 39A switch is a very common special type of argument. Switches almost always start with one or more hyphens ``-`` and alter the way a command operates. For example, the ``ls`` command usually lists the names of all files and directories in the current working directory. By using the ``-l`` switch, the behavior of ``ls`` is changed to not only display the filename, but also the size, permissions, owner, and modification time of each file. 40 41Switches differ between commands and are usually documented on a command's manual page. There are some switches, however, that are common to most commands. For example, ``--help`` will usually display a help text, ``--version`` will usually display the command version, and ``-i`` will often turn on interactive prompting before taking action. 42 43.. _terminology: 44 45Terminology 46----------- 47 48Here we define some of the terms used on this page and throughout the rest of the fish documentation: 49 50- **Argument**: A parameter given to a command. 51 52- **Builtin**: A command that is implemented by the shell. Builtins are so closely tied to the operation of the shell that it is impossible to implement them as external commands. 53 54- **Command**: A program that the shell can run, or more specifically an external program that the shell runs in another process. 55 56- **Function**: A block of commands that can be called as if they were a single command. By using functions, it is possible to string together multiple simple commands into one more advanced command. 57 58- **Job**: A running pipeline or command. 59 60- **Pipeline**: A set of commands strung together so that the output of one command is the input of the next command. 61 62- **Redirection**: An operation that changes one of the input or output streams associated with a job. 63 64- **Switch** or **Option**: A special kind of argument that alters the behavior of a command. A switch almost always begins with one or two hyphens. 65 66.. _quotes: 67 68Quotes 69------ 70 71Sometimes features like :ref:`parameter expansion <expand>` and :ref:`character escapes <escapes>` get in the way. When that happens, you can use quotes, either single (``'``) or double (``"``). Between single quotes, fish performs no expansions. Between double quotes, fish only performs :ref:`variable expansion <expand-variable>`. No other kind of expansion (including :ref:`brace expansion <expand-brace>` or parameter expansion) is performed, and escape sequences (for example, ``\n``) are ignored. Within quotes, whitespace is not used to separate arguments, allowing quoted arguments to contain spaces. 72 73The only meaningful escape sequences in single quotes are ``\'``, which escapes a single quote and ``\\``, which escapes the backslash symbol. The only meaningful escapes in double quotes are ``\"``, which escapes a double quote, ``\$``, which escapes a dollar character, ``\`` followed by a newline, which deletes the backslash and the newline, and ``\\``, which escapes the backslash symbol. 74 75Single quotes have no special meaning within double quotes and vice versa. 76 77Example:: 78 79 rm "cumbersome filename.txt" 80 81removes the file ``cumbersome filename.txt``, while 82 83:: 84 85 rm cumbersome filename.txt 86 87removes two files, ``cumbersome`` and ``filename.txt``. 88 89Another example:: 90 91 grep 'enabled)$' foo.txt 92 93searches for lines ending in ``enabled)`` in ``foo.txt`` (the ``$`` is special to ``grep``: it matches the end of the line). 94 95.. _escapes: 96 97Escaping Characters 98------------------- 99 100Some characters cannot be written directly on the command line. For these characters, so-called escape sequences are provided. These are: 101 102- ``\a`` represents the alert character. 103- ``\e`` represents the escape character. 104- ``\f`` represents the form feed character. 105- ``\n`` represents a newline character. 106- ``\r`` represents the carriage return character. 107- ``\t`` represents the tab character. 108- ``\v`` represents the vertical tab character. 109- ``\xHH``, where ``HH`` is a hexadecimal number, represents the ASCII character with the specified value. For example, ``\x9`` is the tab character. 110- ``\XHH``, where ``HH`` is a hexadecimal number, represents a byte of data with the specified value. If you are using a multibyte encoding, this can be used to enter invalid strings. Only use this if you know what you are doing. 111- ``\ooo``, where ``ooo`` is an octal number, represents the ASCII character with the specified value. For example, ``\011`` is the tab character. 112- ``\uXXXX``, where ``XXXX`` is a hexadecimal number, represents the 16-bit Unicode character with the specified value. For example, ``\u9`` is the tab character. 113- ``\UXXXXXXXX``, where ``XXXXXXXX`` is a hexadecimal number, represents the 32-bit Unicode character with the specified value. For example, ``\U9`` is the tab character. 114- ``\cX``, where ``X`` is a letter of the alphabet, represents the control sequence generated by pressing the control key and the specified letter. For example, ``\ci`` is the tab character 115 116Some characters have special meaning to the shell. For example, an apostrophe ``'`` disables expansion (see :ref:`Quotes<quotes>`). To tell the shell to treat these characters literally, escape them with a backslash. For example, the command:: 117 118 echo \'hello world\' 119 120outputs ``'hello world'`` (including the apostrophes), while the command:: 121 122 echo 'hello world' 123 124outputs ``hello world`` (without the apostrophes). In the former case the shell treats the apostrophes as literal ``'`` characters, while in the latter case it treats them as special expansion modifiers. 125 126The special characters and their escape sequences are: 127 128- :code:`\ ` (backslash space) escapes the space character. This keeps the shell from splitting arguments on the escaped space. 129- ``\$`` escapes the dollar character. 130- ``\\`` escapes the backslash character. 131- ``\*`` escapes the star character. 132- ``\?`` escapes the question mark character (this is not necessary if the ``qmark-noglob`` :ref:`feature flag<featureflags>` is enabled). 133- ``\~`` escapes the tilde character. 134- ``\#`` escapes the hash character. 135- ``\(`` escapes the left parenthesis character. 136- ``\)`` escapes the right parenthesis character. 137- ``\{`` escapes the left curly bracket character. 138- ``\}`` escapes the right curly bracket character. 139- ``\[`` escapes the left bracket character. 140- ``\]`` escapes the right bracket character. 141- ``\<`` escapes the less than character. 142- ``\>`` escapes the more than character. 143- ``\^`` escapes the circumflex character. 144- ``\&`` escapes the ampersand character. 145- ``\|`` escapes the vertical bar character. 146- ``\;`` escapes the semicolon character. 147- ``\"`` escapes the quote character. 148- ``\'`` escapes the apostrophe character. 149 150.. _redirects: 151 152Input/Output Redirection 153----------------------------- 154 155Most programs use three input/output (I/O) streams: 156 157- Standard input (stdin) for reading. Defaults to reading from the keyboard. 158- Standard output (stdout) for writing output. Defaults to writing to the screen. 159- Standard error (stderr) for writing errors and warnings. Defaults to writing to the screen. 160 161Each stream has a number called the file descriptor (FD): 0 for stdin, 1 for stdout, and 2 for stderr. 162 163The destination of a stream can be changed using something called *redirection*. For example, ``echo hello > output.txt``, redirects the standard output of the ``echo`` command to a text file. 164 165- To read standard input from a file, use ``<SOURCE_FILE``. 166- To write standard output to a file, use ``>DESTINATION``. 167- To write standard error to a file, use ``2>DESTINATION``. [#]_ 168- To append standard output to a file, use ``>>DESTINATION_FILE``. 169- To append standard error to a file, use ``2>>DESTINATION_FILE``. 170- To not overwrite ("clobber") an existing file, use ``>?DESTINATION`` or ``2>?DESTINATION``. This is known as the "noclobber" redirection. 171 172``DESTINATION`` can be one of the following: 173 174- A filename. The output will be written to the specified file. Often ``>/dev/null`` to silence output by writing it to the special "sinkhole" file. 175- An ampersand (``&``) followed by the number of another file descriptor like ``&2`` for standard error. The output will be written to the destination descriptor. 176- An ampersand followed by a minus sign (``&-``). The file descriptor will be closed. 177 178As a convenience, the redirection ``&>`` can be used to direct both stdout and stderr to the same destination. For example, ``echo hello &> all_output.txt`` redirects both stdout and stderr to the file ``all_output.txt``. This is equivalent to ``echo hello > all_output.txt 2>&1``. 179 180Any arbitrary file descriptor can used in a redirection by prefixing the redirection with the FD number. 181 182- To redirect the input of descriptor N, use ``N<DESTINATION``. 183- To redirect the output of descriptor N, use ``N>DESTINATION``. 184- To append the output of descriptor N to a file, use ``N>>DESTINATION_FILE``. 185 186For example, ``echo hello 2> output.stderr`` writes the standard error (file descriptor 2) to ``output.stderr``. 187 188It is an error to redirect a builtin, function, or block to a file descriptor above 2. However this is supported for external commands. 189 190.. [#] Previous versions of fish also allowed specifying this as ``^DESTINATION``, but that made another character special so it was deprecated and will be removed in the future. See :ref:`feature flags<featureflags>`. 191 192.. _pipes: 193 194Piping 195------ 196 197Another 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 ``|``. For example:: 198 199 cat foo.txt | head 200 201The command ``cat foo.txt`` sends the contents of ``foo.txt`` to stdout. This output is provided as input for the ``head`` program, which prints the first 10 lines of its input. 202 203It is possible to pipe a different output file descriptor by prepending its FD number and the output redirect symbol to the pipe. For example:: 204 205 make fish 2>| less 206 207will attempt to build ``fish``, and any errors will be shown using the ``less`` pager. [#]_ 208 209As a convenience, the pipe ``&|`` redirects both stdout and stderr to the same process. This is different from bash, which uses ``|&``. 210 211.. [#] A "pager" here is a program that takes output and "paginates" it. ``less`` doesn't just do pages, it allows arbitrary scrolling (even back!). 212 213.. _syntax-job-control: 214 215Job control 216----------- 217 218When you start a job in fish, fish itself will pause, and give control of the terminal to the program just started. Sometimes, you want to continue using the commandline, and have the job run in the background. To create a background job, append an \& (ampersand) to your command. This will tell fish to run the job in the background. Background jobs are very useful when running programs that have a graphical user interface. 219 220Example:: 221 222 emacs & 223 224 225will start the emacs text editor in the background. :ref:`fg <cmd-fg>` can be used to bring it into the foreground again when needed. 226 227Most programs allow you to suspend the program's execution and return control to fish by pressing :kbd:`Control`\ +\ :kbd:`Z` (also referred to as ``^Z``). Once back at the fish commandline, you can start other programs and do anything you want. If you then want you can go back to the suspended command by using the :ref:`fg <cmd-fg>` (foreground) command. 228 229If you instead want to put a suspended job into the background, use the :ref:`bg <cmd-bg>` command. 230 231To get a listing of all currently started jobs, use the :ref:`jobs <cmd-jobs>` command. 232These listed jobs can be removed with the :ref:`disown <cmd-disown>` command. 233 234At the moment, functions cannot be started in the background. Functions that are stopped and then restarted in the background using the :ref:`bg <cmd-bg>` command will not execute correctly. 235 236.. _syntax-function: 237 238Functions 239--------- 240 241Functions are programs written in the fish syntax. They group together various commands and their arguments using a single name. 242 243For example, here's a simple function to list directories:: 244 245 function ll 246 ls -l $argv 247 end 248 249The first line tells fish to define a function by the name of ``ll``, so it can be used by simply writing ``ll`` on the commandline. The second line tells fish that the command ``ls -l $argv`` should be called when ``ll`` is invoked. :ref:`$argv <variables-argv>` is a :ref:`list variable <variables-lists>`, which always contains all arguments sent to the function. In the example above, these are simply passed on to the ``ls`` command. The ``end`` on the third line ends the definition. 250 251Calling this as ``ll /tmp/`` will end up running ``ls -l /tmp/``, which will list the contents of /tmp. 252 253This is a kind of function known as a :ref:`wrapper <syntax-function-wrappers>` or "alias". 254 255Fish's prompt is also defined in a function, called :ref:`fish_prompt <cmd-fish_prompt>`. It is run when the prompt is about to be displayed and its output forms the prompt:: 256 257 function fish_prompt 258 # A simple prompt. Displays the current directory 259 # (which fish stores in the $PWD variable) 260 # and then a user symbol - a '►' for a normal user and a '#' for root. 261 set -l user_char '►' 262 if fish_is_root_user 263 set user_char '#' 264 end 265 266 echo (set_color yellow)$PWD (set_color purple)$user_char 267 end 268 269To edit a function, you can use :ref:`funced <cmd-funced>`, and to save a function :ref:`funcsave <cmd-funcsave>`. This will store it in a function file that fish will :ref:`autoload <syntax-function-autoloading>` when needed. 270 271The :ref:`functions <cmd-functions>` builtin can show a function's current definition (and :ref:`type <cmd-type>` will also do if given a function). 272 273For more information on functions, see the documentation for the :ref:`function <cmd-function>` builtin. 274 275.. _syntax-function-wrappers: 276 277Defining aliases 278^^^^^^^^^^^^^^^^ 279 280One of the most common uses for functions is to slightly alter the behavior of an already existing command. For example, one might want to redefine the ``ls`` command to display colors. The switch for turning on colors on GNU systems is ``--color=auto``. An alias, or wrapper, around ``ls`` might look like this:: 281 282 function ls 283 command ls --color=auto $argv 284 end 285 286There are a few important things that need to be noted about aliases: 287 288- Always take care to add the :ref:`$argv <variables-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. 289 290- If the alias has the same name as the aliased command, you need to prefix the call to the program with ``command`` to tell fish that the function should not call itself, but rather a command with the same name. If you forget to do so, the function would call itself until the end of time. Usually fish is smart enough to figure this out and will refrain from doing so (which is hopefully in your interest). 291 292- Autoloading isn't applicable to aliases. Since, by definition, the function is created at the time the alias command is executed. You cannot autoload aliases. 293 294To easily create a function of this form, you can use the :ref:`alias <cmd-alias>` command. Unlike other shells, this just makes functions - fish has no separate concept of an "alias", we just use the word for a function wrapper like this. 295 296For an alternative, try :ref:`abbreviations <abbreviations>`. These are words that are expanded while you type, instead of being actual functions inside the shell. 297 298.. _syntax-function-autoloading: 299 300Autoloading functions 301^^^^^^^^^^^^^^^^^^^^^ 302 303Functions can be defined on the commandline or in a configuration file, but they can also be automatically loaded. This has some advantages: 304 305- An autoloaded function becomes available automatically to all running shells. 306- If the function definition is changed, all running shells will automatically reload the altered version, after a while. 307- Startup time and memory usage is improved, etc. 308 309When fish needs to load a function, it searches through any directories in the :ref:`list variable <variables-lists>` ``$fish_function_path`` for a file with a name consisting of the name of the function plus the suffix ``.fish`` and loads the first it finds. 310 311For example if you try to execute something called ``banana``, fish will go through all directories in $fish_function_path looking for a file called ``banana.fish`` and load the first one it finds. 312 313By default ``$fish_function_path`` contains the following: 314 315- A directory for users to keep their own functions, usually ``~/.config/fish/functions`` (controlled by the ``XDG_CONFIG_HOME`` environment variable). 316- A directory for functions for all users on the system, usually ``/etc/fish/functions`` (really ``$__fish_sysconfdir/functions``). 317- Directories for other software to put their own functions. These are in the directories in the ``XDG_DATA_DIRS`` environment variable, in a subdirectory called ``fish/vendor_functions.d``. The default is usually ``/usr/share/fish/vendor_functions.d`` and ``/usr/local/share/fish/vendor_functions.d``. 318- The functions shipped with fish, usually installed in ``/usr/share/fish/functions`` (really ``$__fish_data_dir/functions``). 319 320If you are unsure, your functions probably belong in ``~/.config/fish/functions``. 321 322As 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. 323 324Autoloading also won't work for :ref:`event handlers <event>`, 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 :ref:`event handlers <event>` section for more information. 325 326If 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. 327 328If you are developing another program and want to install fish functions for it, install them to the "vendor" functions directory. As this path varies from system to system, you can use ``pkgconfig`` to discover it with the output of ``pkg-config --variable functionsdir fish``. Your installation system should support a custom path to override the pkgconfig path, as other distributors may need to alter it easily. 329 330Comments 331-------- 332 333Anything after a ``#`` until the end of the line is a comment. That means it's purely for the reader's benefit, fish ignores it. 334 335This is useful to explain what and why you are doing something:: 336 337 function ls 338 # The function is called ls, 339 # so we have to explicitly call `command ls` to avoid calling ourselves. 340 command ls --color=auto $argv 341 end 342 343There are no multiline comments. If you want to make a comment span multiple lines, simply start each line with a ``#``. 344 345Comments can also appear after a line like so:: 346 347 set -gx EDITOR emacs # I don't like vim. 348 349.. _syntax-conditional: 350 351Conditions 352---------- 353 354Fish has some builtins that let you execute commands only if a specific criterion is met: :ref:`if <cmd-if>`, :ref:`switch <cmd-switch>`, :ref:`and <cmd-and>` and :ref:`or <cmd-or>`, and also the familiar :ref:`&&/|| <tut-combiners>` syntax. 355 356The :ref:`switch <cmd-switch>` command is used to execute one of possibly many blocks of commands depending on the value of a string. See the documentation for :ref:`switch <cmd-switch>` for more information. 357 358The other conditionals use the :ref:`exit status <variables-status>` of a command to decide if a command or a block of commands should be executed. 359 360Unlike programming languages you might know, :ref:`if <cmd-if>` doesn't take a *condition*, it takes a *command*. If that command returned a successful :ref:`exit status <variables-status>` (that's 0), the ``if`` branch is taken, otherwise the :ref:`else <cmd-else>` branch. 361 362Some examples:: 363 364 # Just see if the file contains the string "fish" anywhere. 365 # This executes the `grep` command, which searches for a string, 366 # and if it finds it returns a status of 0. 367 # The `-q` switch stops it from printing any matches. 368 if grep -q fish myanimals 369 echo "You have fish!" 370 else 371 echo "You don't have fish!" 372 end 373 374 # $XDG_CONFIG_HOME is a standard place to store configuration. 375 # If it's not set applications should use ~/.config. 376 set -q XDG_CONFIG_HOME; and set -l configdir $XDG_CONFIG_HOME 377 or set -l configdir ~/.config 378 379For more, see the documentation for the builtins or the :ref:`Conditionals <tut-conditionals>` section of the tutorial. 380 381.. _syntax-loops-and-blocks: 382 383Loops and blocks 384---------------- 385 386Like most programming language, fish also has the familiar :ref:`while <cmd-while>` and :ref:`for <cmd-for>` loops. 387 388``while`` works like a repeated :ref:`if <cmd-if>`:: 389 390 while true 391 echo Still running 392 sleep 1 393 end 394 395will print "Still running" once a second. You can abort it with ctrl-c. 396 397``for`` loops work like in other shells, which is more like python's for-loops than e.g. C's:: 398 399 for file in * 400 echo file: $file 401 end 402 403will print each file in the current directory. The part after the ``in`` is just a list of arguments, so you can use any :ref:`expansions <expand>` there:: 404 405 set moreanimals bird fox 406 for animal in {cat,}fish dog $moreanimals 407 echo I like the $animal 408 end 409 410If you need a list of numbers, you can use the ``seq`` command to create one:: 411 412 for i in (seq 1 5) 413 echo $i 414 end 415 416:ref:`break <cmd-break>` is available to break out of a loop, and :ref:`continue <cmd-continue>` to jump to the next iteration. 417 418:ref:`Input and output redirections <redirects>` (including :ref:`pipes <pipes>`) can also be applied to loops:: 419 420 while read -l line 421 echo line: $line 422 end < file 423 424In addition there's a :ref:`begin <cmd-begin>` block that just groups commands together so you can redirect to a block or use a new :ref:`variable scope <variables-scope>` without any repetition:: 425 426 begin 427 set -l foo bar # this variable will only be available in this block! 428 end 429 430.. _expand: 431 432Parameter expansion 433------------------- 434 435When fish is given a commandline, it expands the parameters before sending them to the command. There are multiple different kinds of expansions: 436 437- :ref:`Wildcards <expand-wildcard>`, to create filenames from patterns 438- :ref:`Variable expansion <expand-variable>`, to use the value of a variable 439- :ref:`Command substitution <expand-command-substitution>`, to use the output of another command 440- :ref:`Brace expansion <expand-brace>`, to write lists with common pre- or suffixes in a shorter way 441- :ref:`Tilde expansion <expand-home>`, to turn the ``~`` at the beginning of paths into the path to the home directory 442 443Parameter expansion is limited to 524288 items. There is a limit to how many arguments the operating system allows for any command, and 524288 is far above it. This is a measure to stop the shell from hanging doing useless computation. 444 445.. _expand-wildcard: 446 447Wildcards ("Globbing") 448^^^^^^^^^^^^^^^^^^^^^^ 449 450When a parameter includes an :ref:`unquoted <quotes>` ``*`` star (or "asterisk") or a ``?`` question mark, fish uses it as a wildcard to match files. 451 452- ``*`` matches any number of characters (including zero) in a file name, not including ``/``. 453 454- ``**`` matches any number of characters (including zero), and also descends into subdirectories. If ``**`` is a segment by itself, that segment may match zero times, for compatibility with other shells. 455 456- ``?`` can match any single character except ``/``. This is deprecated and can be disabled via the ``qmark-noglob`` :ref:`feature flag<featureflags>`, so ``?`` will just be an ordinary character. 457 458Other shells, such as zsh, have a much richer glob syntax, like ``**(.)`` to only match regular files. Fish does not. Instead of reinventing the wheel, use programs like ``find`` to look for files. For example:: 459 460 function ff --description 'Like ** but only returns plain files.' 461 # This also ignores .git directories. 462 find . \( -name .git -type d -prune \) -o -type f | \ 463 sed -n -e '/^\.\/\.git$/n' -e 's/^\.\///p' 464 end 465 466You would then use it in place of ``**`` like this, ``my_prog (ff)``, to pass only regular files in or below $PWD to ``my_prog``. [#]_ 467 468Wildcard matches are sorted case insensitively. When sorting matches containing numbers, they are naturally sorted, so that the strings '1' '5' and '12' would be sorted like 1, 5, 12. 469 470Hidden files (where the name begins with a dot) are not considered when wildcarding unless the wildcard string has a dot in that place. 471 472Examples: 473 474- ``a*`` matches any files beginning with an 'a' in the current directory. 475 476- ``???`` matches any file in the current directory whose name is exactly three characters long. 477 478- ``**`` matches any files and directories in the current directory and all of its subdirectories. 479 480- ``~/.*`` matches all hidden files (also known as "dotfiles") and directories in your home directory. 481 482For most commands, if any wildcard fails to expand, the command is not executed, :ref:`$status <variables-status>` is set to nonzero, and a warning is printed. This behavior is like what bash does with ``shopt -s failglob``. There are exactly 4 exceptions, namely :ref:`set <cmd-set>`, overriding variables in :ref:`overrides <variables-override>`, :ref:`count <cmd-count>` and :ref:`for <cmd-for>`. Their globs will instead expand to zero arguments (so the command won't see them at all), like with ``shopt -s nullglob`` in bash. 483 484Examples:: 485 486 # List the .foo files, or warns if there aren't any. 487 ls *.foo 488 489 # List the .foo files, if any. 490 set foos *.foo 491 if count $foos >/dev/null 492 ls $foos 493 end 494 495.. [#] Technically, unix allows filenames with newlines, and this splits the ``find`` output on newlines. If you want to avoid that, use find's ``-print0`` option and :ref:`string split0<cmd-string-split0>`. 496 497.. _expand-variable: 498 499Variable expansion 500^^^^^^^^^^^^^^^^^^ 501 502One of the most important expansions in fish is the "variable expansion". This is the replacing of a dollar sign (``$``) followed by a variable name with the _value_ of that variable. For more on shell variables, read the :ref:`Shell variables <variables>` section. 503 504In the simplest case, this is just something like:: 505 506 echo $HOME 507 508which will replace ``$HOME`` with the home directory of the current user, and pass it to :ref:`echo <cmd-echo>`, which will then print it. 509 510Some variables like ``$HOME`` are already set because fish sets them by default or because fish's parent process passed them to fish when it started it. You can define your own variables by setting them with :ref:`set <cmd-set>`:: 511 512 set my_directory /home/cooluser/mystuff 513 ls $my_directory 514 # shows the contents of /home/cooluser/mystuff 515 516For more on how setting variables works, see :ref:`Shell variables <variables>` and the following sections. 517 518Sometimes a variable has no value because it is undefined or empty, and it expands to nothing:: 519 520 521 echo $nonexistentvariable 522 # Prints no output. 523 524To separate a variable name from text you can encase the variable within double-quotes or braces:: 525 526 set WORD cat 527 echo The plural of $WORD is "$WORD"s 528 # Prints "The plural of cat is cats" because $WORD is set to "cat". 529 echo The plural of $WORD is {$WORD}s 530 # ditto 531 532Without the quotes or braces, fish will try to expand a variable called ``$WORDs``, which may not exist. 533 534The latter syntax ``{$WORD}`` is a special case of :ref:`brace expansion <expand-brace>`. 535 536If $WORD here is undefined or an empty list, the "s" is not printed. However, it is printed if $WORD is the empty string (like after ``set WORD ""``). 537 538Unlike all the other expansions, variable expansion also happens in double quoted strings. Inside double quotes (``"these"``), variables will always expand to exactly one argument. If they are empty or undefined, it will result in an empty string. If they have one element, they'll expand to that element. If they have more than that, the elements will be joined with spaces, unless the variable is a :ref:`path variable <variables-path>` - in that case it will use a colon (`:`) instead [#]_. 539 540Outside of double quotes, variables will expand to as many arguments as they have elements. That means an empty list will expand to nothing, a variable with one element will expand to that element, and a variable with multiple elements will expand to each of those elements separately. 541 542If a variable expands to nothing, it will cancel out any other strings attached to it. See the :ref:`cartesian product <cartesian-product>` section for more information. 543 544The ``$`` symbol can also be used multiple times, as a kind of "dereference" operator (the ``*`` in C or C++), like in the following code:: 545 546 set foo a b c 547 set a 10; set b 20; set c 30 548 for i in (seq (count $$foo)) 549 echo $$foo[$i] 550 end 551 552 # Output is: 553 # 10 554 # 20 555 # 30 556 557``$$foo[$i]`` is "the value of the variable named by ``$foo[$i]``. 558 559When using this feature together with list brackets, the brackets will be used from the inside out. ``$$foo[5]`` will use the fifth element of ``$foo`` as a variable name, instead of giving the fifth element of all the variables $foo refers to. That would instead be expressed as ``$$foo[1][5]`` (take the first element of ``$foo``, use it as a variable name, then give the fifth element of that). 560 561.. [#] Unlike bash or zsh, which will join with the first character of $IFS (which usually is space). 562 563.. _expand-command-substitution: 564 565Command substitution 566^^^^^^^^^^^^^^^^^^^^ 567 568The output of a command (or an entire :ref:`pipeline <pipes>`) can be used as the arguments to another command. 569 570When you write a command in parenthesis like ``outercommand (innercommand)``, the ``innercommand`` will be executed first. Its output will be taken and each line given as a separate argument to ``outercommand``, which will then be executed. [#]_ 571 572If the output is piped to :ref:`string split or string split0 <cmd-string-split>` as the last step, those splits are used as they appear instead of splitting lines. 573 574The exit status of the last run command substitution is available in the :ref:`status <variables-status>` variable if the substitution happens in the context of a :ref:`set <cmd-set>` command (so ``if set -l (something)`` checks if ``something`` returned true). 575 576Only part of the output can be used, see :ref:`index range expansion <expand-index-range>` for details. 577 578Fish has a default limit of 100 MiB on the data it will read in a command sustitution. If that limit is reached the command (all of it, not just the command substitution - the outer command won't be executed at all) fails and ``$status`` is set to 122. This is so command substitutions can't cause the system to go out of memory, because typically your operating system has a much lower limit, so reading more than that would be useless and harmful. This limit can be adjusted with the ``fish_read_limit`` variable (`0` meaning no limit). This limit also affects the :ref:`read <cmd-read>` command. 579 580Examples:: 581 582 # Outputs 'image.png'. 583 echo (basename image.jpg .jpg).png 584 585 # Convert all JPEG files in the current directory to the 586 # PNG format using the 'convert' program. 587 for i in *.jpg; convert $i (basename $i .jpg).png; end 588 589 # Set the ``data`` variable to the contents of 'data.txt' 590 # without splitting it into a list. 591 begin; set -l IFS; set data (cat data.txt); end 592 593 # Set ``$data`` to the contents of data, splitting on NUL-bytes. 594 set data (cat data | string split0) 595 596 597Sometimes you want to pass the output of a command to another command that only accepts files. If it's just one file, you can usually just pass it via a pipe, like:: 598 599 grep fish myanimallist1 | wc -l 600 601but if you need multiple or the command doesn't read from standard input, "process substitution" is useful. Other shells [#]_ allow this via ``foo <(bar) <(baz)``, and fish uses the :ref:`psub <cmd-psub>` command:: 602 603 # Compare just the lines containing "fish" in two files: 604 diff -u (grep fish myanimallist1 | psub) (grep fish myanimallist2 | psub) 605 606This creates a temporary file, stores the output of the command in that file and prints the filename, so it is given to the outer command. 607 608.. [#] Setting ``$IFS`` to empty will disable line splitting. This is deprecated, use :ref:`string split <cmd-string-split>` instead. 609.. [#] Bash and Zsh at least, though it is a POSIX extension 610 611.. _expand-brace: 612 613Brace expansion 614^^^^^^^^^^^^^^^ 615 616Curly braces can be used to write comma-separated lists. They will be expanded with each element becoming a new parameter, with the surrounding string attached. This is useful to save on typing, and to separate a variable name from surrounding text. 617 618Examples:: 619 620 > echo input.{c,h,txt} 621 input.c input.h input.txt 622 623 # Move all files with the suffix '.c' or '.h' to the subdirectory src. 624 > mv *.{c,h} src/ 625 626 # Make a copy of `file` at `file.bak`. 627 > cp file{,.bak} 628 629 > set -l dogs hot cool cute "good " 630 > echo {$dogs}dog 631 hotdog cooldog cutedog good dog 632 633If there is no "," or variable expansion between the curly braces, they will not be expanded:: 634 635 # This {} isn't special 636 > echo foo-{} 637 foo-{} 638 # This passes "HEAD@{2}" to git 639 > git reset --hard HEAD@{2} 640 > echo {{a,b}} 641 {a} {b} # because the inner brace pair is expanded, but the outer isn't. 642 643If after expansion there is nothing between the braces, the argument will be removed (see :ref:`the cartesian product section <cartesian-product>`):: 644 645 > echo foo-{$undefinedvar} 646 # Output is an empty line, just like a bare `echo`. 647 648If there is nothing between a brace and a comma or two commas, it's interpreted as an empty element:: 649 650 > echo {,,/usr}/bin 651 /bin /bin /usr/bin 652 653To use a "," as an element, :ref:`quote <quotes>` or :ref:`escape <escapes>` it. 654 655.. _cartesian-product: 656 657Combining lists (Cartesian Product) 658^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 659 660When lists are expanded with other parts attached, they are expanded with these parts still attached. Even if two lists are attached to each other, they are expanded in all combinations. This is referred to as the `cartesian product` (like in mathematics), and works basically like :ref:`brace expansion <expand-brace>`. 661 662Examples:: 663 664 # Brace expansion is the most familiar: 665 # All elements in the brace combine with the parts outside of the braces 666 >_ echo {good,bad}" apples" 667 good apples bad apples 668 669 # The same thing happens with variable expansion. 670 >_ set -l a x y z 671 >_ set -l b 1 2 3 672 673 # $a is {x,y,z}, $b is {1,2,3}, 674 # so this is `echo {x,y,z}{1,2,3}` 675 >_ echo $a$b 676 x1 y1 z1 x2 y2 z2 x3 y3 z3 677 678 # Same thing if something is between the lists 679 >_ echo $a"-"$b 680 x-1 y-1 z-1 x-2 y-2 z-2 x-3 y-3 z-3 681 682 # Or a brace expansion and a variable 683 >_ echo {x,y,z}$b 684 x1 y1 z1 x2 y2 z2 x3 y3 z3 685 686 # A combined brace-variable expansion 687 >_ echo {$b}word 688 1word 2word 3word 689 690 # Special case: If $c has no elements, this expands to nothing 691 >_ echo {$c}word 692 # Output is an empty line 693 694Sometimes this may be unwanted, especially that tokens can disappear after expansion. In those cases, you should double-quote variables - ``echo "$c"word``. 695 696This also happens after :ref:`command substitution <expand-command-substitution>`. To avoid tokens disappearing there, make the inner command return a trailing newline, or store the output in a variable and double-quote it. 697 698E.g. 699 700:: 701 702 >_ set b 1 2 3 703 >_ echo (echo x)$b 704 x1 x2 x3 705 >_ echo (printf '%s' '')banana 706 # the printf prints nothing, so this is nothing times "banana", 707 # which is nothing. 708 >_ echo (printf '%s\n' '')banana 709 # the printf prints a newline, 710 # so the command substitution expands to an empty string, 711 # so this is `''banana` 712 banana 713 714This can be quite useful. For example, if you want to go through all the files in all the directories in $PATH, use:: 715 716 for file in $PATH/* 717 718Because :ref:`$PATH <path>` is a list, this expands to all the files in all the directories in it. And if there are no directories in $PATH, the right answer here is to expand to no files. 719 720.. _expand-index-range: 721 722Index range expansion 723^^^^^^^^^^^^^^^^^^^^^ 724 725Sometimes it's necessary to access only some of the elements of a :ref:`list <variables-lists>` (all fish variables are lists), or some of the lines a :ref:`command substitution <expand-command-substitution>` outputs. Both are possible in fish by writing a set of indices in brackets, like:: 726 727 # Make $var a list of four elements 728 set var one two three four 729 # Print the second: 730 echo $var[2] 731 # prints "two" 732 # or print the first three: 733 echo $var[1..3] 734 # prints "one two three" 735 736In index brackets, fish understands ranges written like ``a..b`` ('a' and 'b' being indices). They are expanded into a sequence of indices from a to b (so ``a a+1 a+2 ... b``), going up if b is larger and going down if a is larger. Negative indices can also be used - they are taken from the end of the list, so ``-1`` is the last element, and ``-2`` the one before it. If an index doesn't exist the range is clamped to the next possible index. 737 738If a list has 5 elements the indices go from 1 to 5, so a range of ``2..16`` will only go from element 2 to element 5. 739 740If the end is negative the range always goes up, so ``2..-2`` will go from element 2 to 4, and ``2..-16`` won't go anywhere because there is no way to go from the second element to one that doesn't exist, while going up. 741If the start is negative the range always goes down, so ``-2..1`` will go from element 4 to 1, and ``-16..2`` won't go anywhere because there is no way to go from an element that doesn't exist to the second element, while going down. 742 743A missing starting index in a range defaults to 1. This is allowed if the range is the first index expression of the sequence. Similarly, a missing ending index, defaulting to -1 is allowed for the last index range in the sequence. 744 745Multiple ranges are also possible, separated with a space. 746 747Some examples:: 748 749 750 echo (seq 10)[1 2 3] 751 # Prints: 1 2 3 752 753 # Limit the command substitution output 754 echo (seq 10)[2..5] 755 # Uses elements from 2 to 5 756 # Output is: 2 3 4 5 757 758 echo (seq 10)[7..] 759 # Prints: 7 8 9 10 760 761 # Use overlapping ranges: 762 echo (seq 10)[2..5 1..3] 763 # Takes elements from 2 to 5 and then elements from 1 to 3 764 # Output is: 2 3 4 5 1 2 3 765 766 # Reverse output 767 echo (seq 10)[-1..1] 768 # Uses elements from the last output line to 769 # the first one in reverse direction 770 # Output is: 10 9 8 7 6 5 4 3 2 1 771 772 # The command substitution has only one line, 773 # so these will result in empty output: 774 echo (echo one)[2..-1] 775 echo (echo one)[-3..1] 776 777The same works when setting or expanding variables:: 778 779 780 # Reverse path variable 781 set PATH $PATH[-1..1] 782 # or 783 set PATH[-1..1] $PATH 784 785 # Use only n last items of the PATH 786 set n -3 787 echo $PATH[$n..-1] 788 789Variables can be used as indices for expansion of variables, like so:: 790 791 set index 2 792 set letters a b c d 793 echo $letters[$index] # returns 'b' 794 795However using variables as indices for command substitution is currently not supported, so:: 796 797 echo (seq 5)[$index] # This won't work 798 799 set sequence (seq 5) # It needs to be written on two lines like this. 800 echo $sequence[$index] # returns '2' 801 802When using indirect variable expansion with multiple ``$`` (``$$name``), you have to give all indices up to the variable you want to slice:: 803 804 > set -l list 1 2 3 4 5 805 > set -l name list 806 > echo $$name[1] 807 1 2 3 4 5 808 > echo $$name[1..-1][1..3] # or $$name[1][1..3], since $name only has one element. 809 1 2 3 810 811.. _expand-home: 812 813Home directory expansion 814^^^^^^^^^^^^^^^^^^^^^^^^ 815 816The ``~`` (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:: 817 818 ls ~/Music # lists my music directory 819 820 echo ~root # prints root's home directory, probably "/root" 821 822 823.. _combine: 824 825Combining different expansions 826^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 827 828All of the above expansions can be combined. If several expansions result in more than one parameter, all possible combinations are created. 829 830When combining multiple parameter expansions, expansions are performed in the following order: 831 832- Command substitutions 833- Variable expansions 834- Bracket expansion 835- Wildcard expansion 836 837Expansions are performed from right to left, nested bracket expansions are performed from the inside and out. 838 839Example: 840 841If 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``. 842 843.. _variables: 844 845Shell variables 846--------------- 847 848Variables are a way to save data and pass it around. They can be used just by the shell, or they can be ":ref:`exported <variables-export>`", 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". 849 850To set a variable value, use the :ref:`set <cmd-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. 851 852Example: 853 854To set the variable ``smurf_color`` to the value ``blue``, use the command ``set smurf_color blue``. 855 856After a variable has been set, you can use the value of a variable in the shell through :ref:`variable expansion <expand-variable>`. 857 858Example:: 859 860 set smurf_color blue 861 echo Smurfs are usually $smurf_color 862 set pants_color red 863 echo Papa smurf, who is $smurf_color, wears $pants_color pants 864 865So you set a variable with ``set``, and use it with a ``$`` and the name. 866 867.. _variables-scope: 868 869Variable scope 870^^^^^^^^^^^^^^ 871 872There are three kinds of variables in fish: universal, global and local variables. 873 874- Universal variables are shared between all fish sessions a user is running on one computer. 875- Global variables are specific to the current fish session, and will never be erased unless explicitly requested by using ``set -e``. 876- Local variables are specific to the current fish session, and associated with a specific 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``. 877 878Variables can be explicitly set to be universal with the ``-U`` or ``--universal`` switch, global with the ``-g`` or ``--global`` switch, or local with the ``-l`` or ``--local`` switch. The scoping rules when creating or updating a variable are: 879 880- 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. 881 882- 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. 883 884- As a special case, when no scope is given and no variable has been defined the variable will belong to the scope of the currently executing *function*. This is different from the ``--local`` flag, which would make the variable local to the current *block*. 885 886There can be many variables with the same name, but different scopes. When you :ref:`use a variable <expand-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. 887 888 889Example: 890 891There are a few possible uses for different scopes. 892 893Typically inside funcions you should use local scope:: 894 895 function something 896 set -l file /path/to/my/file 897 if not test -e "$file" 898 set file /path/to/my/otherfile 899 end 900 end 901 902If 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:: 903 904 # Don't shorten the working directory in the prompt 905 set -g fish_prompt_pwd_dir_length 0 906 907 # Set my preferred cursor style: 908 function setcursors 909 set -g fish_cursor_default block 910 set -g fish_cursor_insert line 911 set -g fish_cursor_visual underscore 912 end 913 914 # Set my language 915 set -gx LANG de_DE.UTF-8 916 917If you want to set some personal customization, universal variables are nice:: 918 919 # Typically you'd run this interactively, fish takes care of keeping it. 920 set -U fish_color_autosuggestion 555 921 922Here is an example of local vs function-scoped variables:: 923 924 begin 925 # This is a nice local scope where all variables will die 926 set -l pirate 'There be treasure in them thar hills' 927 set captain Space, the final frontier 928 end 929 930 echo $pirate 931 # This will not output anything, since the pirate was local 932 echo $captain 933 # This will output the good Captain's speech since $captain had function-scope. 934 935.. _variables-override: 936 937Overriding variables for a single command 938^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 939 940If you want to override a variable for a single command, you can use "var=val" statements before the command:: 941 942 # Call git status on another directory 943 # (can also be done via `git -C somerepo status`) 944 GIT_DIR=somerepo git status 945 946Unlike other shells, fish will first set the variable and then perform other expansions on the line, so:: 947 948 set foo banana 949 foo=gagaga echo $foo # prints gagaga, while in other shells it might print "banana" 950 951Multiple elements can be given in a :ref:`brace expansion<expand-brace>`:: 952 953 # Call bash with a reasonable default path. 954 PATH={/usr,}/{s,}bin bash 955 956Or with a :ref:`glob <expand-wildcard>`:: 957 958 # Run vlc on all mp3 files in the current directory 959 # If no file exists it will still be run with no arguments 960 mp3s=*.mp3 vlc $mp3s 961 962Unlike 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. 963 964This syntax is supported since fish 3.1. 965 966.. _variables-universal: 967 968More on universal variables 969^^^^^^^^^^^^^^^^^^^^^^^^^^^ 970 971Universal variables are variables that are shared between all the user's fish sessions on the computer. Fish stores many of its configuration options as universal variables. This means that in order to change fish settings, all you have to do is change the variable value once, and it will be automatically updated for all sessions, and preserved across computer reboots and login/logout. 972 973To see universal variables in action, start two fish sessions side by side, and issue the following command in one of them ``set fish_color_cwd blue``. Since ``fish_color_cwd`` is a universal variable, the color of the current working directory listing in the prompt will instantly change to blue on both terminals. 974 975:ref:`Universal variables <variables-universal>` 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. 976 977Do not append to universal variables in :ref:`config.fish <configuration>`, because these variables will then get longer with each new shell instance. Instead, simply set them once at the command line. 978 979 980.. _variables-functions: 981 982Variable scope for functions 983^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 984 985When calling a function, all current local 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. 986 987For example:: 988 989 function shiver 990 set phrase 'Shiver me timbers' 991 end 992 993 function avast 994 set --local phrase 'Avast, mateys' 995 # Calling the shiver function here can not 996 # change any variables in the local scope 997 shiver 998 echo $phrase 999 end 1000 avast 1001 1002 # Outputs "Avast, mateys" 1003 1004 1005 1006.. _variables-export: 1007 1008Exporting variables 1009^^^^^^^^^^^^^^^^^^^ 1010 1011Variables 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 $LESS 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. 1012 1013This also applies to fish - when it starts up, it receives environment variables from its parent (usually the terminal). These typically include system configuration like :ref:`$PATH <PATH>` and :ref:`locale variables <variables-locale>`. 1014 1015Variables 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 identical to the scoping rules for variables: 1016 1017- If a variable is explicitly set to either be exported or not exported, that setting will be honored. 1018 1019- 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. 1020 1021- Otherwise, by default, the variable will not be exported. 1022 1023- If a variable has local scope and is exported, any function called receives a *copy* of it, so any changes it makes to the variable disappear once the function returns. 1024 1025- Global variables are accessible to functions whether they are exported or not. 1026 1027As a naming convention, exported variables are in uppercase and unexported variables are in lowercase. 1028 1029For example:: 1030 1031 set -gx ANDROID_HOME ~/.android # /opt/android-sdk 1032 set -gx CDPATH . ~ (test -e ~/Videos; and echo ~/Videos) 1033 set -gx EDITOR emacs -nw 1034 set -gx GOPATH ~/dev/go 1035 set -gx GTK2_RC_FILES "$XDG_CONFIG_HOME/gtk-2.0/gtkrc" 1036 set -gx LESSHISTFILE "-" 1037 1038Note: Exporting is not a :ref:`scope <variables-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 :ref:`Overrides <variables-override>`. They are *copied* to functions so the function can't alter them outside, and still available to commands. 1039 1040.. _variables-lists: 1041 1042Lists 1043^^^^^ 1044 1045Fish can store a list (or an "array" if you wish) of multiple strings inside of a variable:: 1046 1047 > set mylist first second third 1048 > printf '%s\n' $mylist # prints each element on its own line 1049 first 1050 second 1051 third 1052 1053To access one element of a list, use the index of the element inside of square brackets, like this:: 1054 1055 echo $PATH[3] 1056 1057List indices start at 1 in fish, not 0 like in other languages. This is because it requires less subtracting of 1 and many common Unix tools like ``seq`` work better with it (``seq 5`` prints 1 to 5, not 0 to 5). An invalid index is silently ignored resulting in no value (not even an empty string, just no argument at all). 1058 1059If 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``:: 1060 1061 for i in $PATH 1062 echo $i is in the path 1063 end 1064 1065This goes over every directory in $PATH separately and prints a line saying it is in the path. 1066 1067To create a variable ``smurf``, containing the items ``blue`` and ``small``, simply write:: 1068 1069 set smurf blue small 1070 1071It is also possible to set or erase individual elements of a list:: 1072 1073 # Set smurf to be a list with the elements 'blue' and 'small' 1074 set smurf blue small 1075 1076 # Change the second element of smurf to 'evil' 1077 set smurf[2] evil 1078 1079 # Erase the first element 1080 set -e smurf[1] 1081 1082 # Output 'evil' 1083 echo $smurf 1084 1085 1086If 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:: 1087 1088 > set fruit apple orange banana 1089 > echo $fruit[-1] 1090 banana 1091 1092 > echo $fruit[-2..-1] 1093 orange 1094 banana 1095 1096 > echo $fruit[-1..1] # reverses the list 1097 banana 1098 orange 1099 apple 1100 1101As you see, you can use a range of indices, see :ref:`index range expansion <expand-index-range>` for details. 1102 1103All lists are one-dimensional and can't contain other lists, although it is possible to fake nested lists using dereferencing - see :ref:`variable expansion <expand-variable>`. 1104 1105When a list is exported as an environment variable, it is either space or colon delimited, depending on whether it is a :ref:`path variable <variables-path>`:: 1106 1107 > set -x smurf blue small 1108 > set -x smurf_PATH forest mushroom 1109 > env | grep smurf 1110 smurf=blue small 1111 smurf_PATH=forest:mushroom 1112 1113Fish 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. 1114 1115Lists can be inspected with the :ref:`count <cmd-count>` or the :ref:`contains <cmd-contains>` commands:: 1116 1117 count $smurf 1118 # 2 1119 1120 contains blue $smurf 1121 # key found, exits with status 0 1122 1123 > contains -i blue $smurf 1124 1 1125 1126A nice thing about lists is that they are passed to commands one element as one argument, so once you've set your list, you can just pass it:: 1127 1128 set -l grep_args -r "my string" 1129 grep $grep_args . # will run the same as `grep -r "my string"` . 1130 1131Unlike other shells, fish does not do "word splitting" - elements in a list stay as they are, even if they contain spaces or tabs. 1132 1133.. _variables-argv: 1134 1135Argument Handling 1136^^^^^^^^^^^^^^^^^ 1137 1138An important list is ``$argv``, which contains the arguments to a function or script. For example:: 1139 1140 function myfunction 1141 echo $argv[1] 1142 echo $argv[3] 1143 end 1144 1145This function takes whatever arguments it gets and prints the first and third:: 1146 1147 > myfunction first second third 1148 first 1149 third 1150 1151 > myfunction apple cucumber banana 1152 apple 1153 banana 1154 1155Commandline tools often get various options and flags and positional arguments, and $argv would contain all of these. 1156 1157A more robust approach to argument handling is :ref:`argparse <cmd-argparse>`, which checks the defined options and puts them into various variables, leaving only the positional arguments in $argv. Here's a simple example:: 1158 1159 function mybetterfunction 1160 argparse h/help s/second -- $argv 1161 or return # exit if argparse failed because it found an option it didn't recognize - it will print an error 1162 1163 # If -h or --help is given, we print a little help text and return 1164 if set -q _flag_help 1165 echo "mybetterfunction [-h|--help] [-s|--second] [ARGUMENTS...]" 1166 return 0 1167 end 1168 1169 # If -s or --second is given, we print the second argument, 1170 # not the first and third. 1171 if set -q _flag_second 1172 echo $argv[2] 1173 else 1174 echo $argv[1] 1175 echo $argv[3] 1176 end 1177 end 1178 1179The options will be *removed* from $argv, so $argv[2] is the second *positional* argument now:: 1180 1181 > mybetterfunction first -s second third 1182 second 1183 1184.. _variables-path: 1185 1186PATH variables 1187^^^^^^^^^^^^^^ 1188 1189Path variables are a special kind of variable used to support colon-delimited path lists including PATH, CDPATH, MANPATH, PYTHONPATH, etc. All variables that end in "PATH" (case-sensitive) become PATH variables. 1190 1191PATH variables act as normal lists, except they are implicitly joined and split on colons. 1192 1193:: 1194 1195 set MYPATH 1 2 3 1196 echo "$MYPATH" 1197 # 1:2:3 1198 set MYPATH "$MYPATH:4:5" 1199 echo $MYPATH 1200 # 1 2 3 4 5 1201 echo "$MYPATH" 1202 # 1:2:3:4:5 1203 1204Variables can be marked or unmarked as PATH variables via the ``--path`` and ``--unpath`` options to ``set``. 1205 1206.. _variables-special: 1207 1208Special variables 1209^^^^^^^^^^^^^^^^^ 1210 1211You can change the settings of fish by changing the values of certain variables. 1212 1213.. _PATH: 1214 1215- ``PATH``, a list of directories in which to search for commands 1216 1217- ``CDPATH``, a list of directories in which the :ref:`cd <cmd-cd>` builtin looks for a new directory. 1218 1219- The locale variables ``LANG``, ``LC_ALL``, ``LC_COLLATE``, ``LC_CTYPE``, ``LC_MESSAGES``, ``LC_MONETARY``, ``LC_NUMERIC`` and ``LC_TIME`` set the language option for the shell and subprograms. See the section :ref:`Locale variables <variables-locale>` for more information. 1220 1221- A number of variable starting with the prefixes ``fish_color`` and ``fish_pager_color``. See :ref:`Variables for changing highlighting colors <variables-color>` for more information. 1222 1223- ``fish_ambiguous_width`` controls the computed width of ambiguous-width characters. This should be set to 1 if your terminal renders these characters as single-width (typical), or 2 if double-width. 1224 1225- ``fish_emoji_width`` controls whether fish assumes emoji render as 2 cells or 1 cell wide. This is necessary because the correct value changed from 1 to 2 in Unicode 9, and some terminals may not be aware. Set this if you see graphical glitching related to emoji (or other "special" characters). It should usually be auto-detected. 1226 1227- ``FISH_DEBUG`` and ``FISH_DEBUG_OUTPUT`` control what debug output fish generates and where it puts it, analogous to the ``--debug`` and ``--debug-output`` options. These have to be set on startup, via e.g. ``FISH_DEBUG='reader*' FISH_DEBUG_OUTPUT=/tmp/fishlog fish``. 1228 1229- ``fish_escape_delay_ms`` sets how long fish waits for another key after seeing an escape, to distinguish pressing the escape key from the start of an escape sequence. The default is 30ms. Increasing it increases the latency but allows pressing escape instead of alt for alt+character bindings. For more information, see :ref:`the chapter in the bind documentation <cmd-bind-escape>`. 1230 1231- ``fish_greeting``, the greeting message printed on startup. This is printed by a function of the same name that can be overridden for more complicated changes (see :ref:`funced <cmd-funced>` 1232 1233- ``fish_handle_reflow``, determines whether fish should try to repaint the commandline when the terminal resizes. In terminals that reflow text this should be disabled. Set it to 1 to enable, anything else to disable. 1234 1235- ``fish_history``, the current history session name. If set, all subsequent commands within an 1236 interactive fish session will be logged to a separate file identified by the value of the 1237 variable. If unset, the default session name "fish" is used. If set to an 1238 empty string, history is not saved to disk (but is still available within the interactive 1239 session). 1240 1241- ``fish_key_bindings``, the name of the function that sets up the keyboard shortcuts for the :ref:`command-line editor <editor>`. 1242 1243- ``fish_trace``, if set and not empty, will cause fish to print commands before they execute, similar to ``set -x`` in bash. The trace is printed to the path given by the :ref:`--debug-output <cmd-fish>` option to fish (stderr by default). 1244 1245- ``fish_user_paths``, a list of directories that are prepended to ``PATH``. This can be a universal variable. 1246 1247- ``umask``, the current file creation mask. The preferred way to change the umask variable is through the :ref:`umask <cmd-umask>` function. An attempt to set umask to an invalid value will always fail. 1248 1249- ``BROWSER``, your preferred web browser. If this variable is set, fish will use the specified browser instead of the system default browser to display the fish documentation. 1250 1251Fish 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``. 1252 1253- ``_``, the name of the currently running command (though this is deprecated, and the use of ``status current-command`` is preferred). 1254 1255- ``argv``, a list of arguments to the shell or function. ``argv`` is only defined when inside a function call, or if fish was invoked with a list of arguments, like ``fish myscript.fish foo bar``. This variable can be changed. 1256 1257- ``CMD_DURATION``, the runtime of the last command in milliseconds. 1258 1259- ``COLUMNS`` and ``LINES``, the current size of the terminal in height and width. These values are only used by fish if the operating system does not report the size of the terminal. Both variables must be set in that case otherwise a default of 80x24 will be used. They are updated when the window size changes. 1260 1261- ``fish_kill_signal``, the signal that terminated the last foreground job, or 0 if the job exited normally. 1262 1263- ``fish_pid``, the process ID (PID) of the shell. 1264 1265- ``history``, a list containing the last commands that were entered. 1266 1267- ``HOME``, the user's home directory. This variable can be changed. 1268 1269- ``hostname``, the machine's hostname. 1270 1271- ``IFS``, the internal field separator that is used for word splitting with the :ref:`read <cmd-read>` builtin. Setting this to the empty string will also disable line splitting in :ref:`command substitution <expand-command-substitution>`. This variable can be changed. 1272 1273- ``last_pid``, the process ID (PID) of the last background process. 1274 1275- ``PWD``, the current working directory. 1276 1277- ``pipestatus``, a list of exit statuses of all processes that made up the last executed pipe. See :ref:`exit status <variables-status>`. 1278 1279- ``SHLVL``, the level of nesting of shells. Fish increments this in interactive shells, otherwise it simply passes it along. 1280 1281- ``status``, the :ref:`exit status <variables-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. 1282 1283- ``status_generation``, the "generation" count of ``$status``. This will be incremented only when the previous command produced an explicit status. (For example, background jobs will not increment this). 1284 1285- ``USER``, the current username. This variable can be changed. 1286 1287- ``version``, the version of the currently running fish (also available as ``FISH_VERSION`` for backward compatibility). 1288 1289- ``fish_killring``, list of entries in fish kill ring. 1290 1291As 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. 1292 1293Fish also uses some variables internally, their name usually starting with ``__fish``. These are internal and should not typically be modified directly. 1294 1295.. _variables-status: 1296 1297The status variable 1298^^^^^^^^^^^^^^^^^^^ 1299 1300Whenever 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. 1301 1302Fish stores the exit status of the last process in the last job to exit in the ``status`` variable. 1303 1304If fish encounters a problem while executing a command, the status variable may also be set to a specific value: 1305 1306- 0 is generally the exit status of commands if they successfully performed the requested operation. 1307 1308- 1 is generally the exit status of commands if they failed to perform the requested operation. 1309 1310- 121 is generally the exit status of commands if they were supplied with invalid arguments. 1311 1312- 123 means that the command was not executed because the command name contained invalid characters. 1313 1314- 124 means that the command was not executed because none of the wildcards in the command produced any matches. 1315 1316- 125 means that while an executable with the specified name was located, the operating system could not actually execute the command. 1317 1318- 126 means that while a file with the specified name was located, it was not executable. 1319 1320- 127 means that no function, builtin or command with the given name could be located. 1321 1322If a process exits through a signal, the exit status will be 128 plus the number of the signal. 1323 1324The status can be negated with :ref:`not <cmd-not>` (or ``!``), which is useful in a :ref:`condition <syntax-conditional>`. This turns a status of 0 into 1 and any non-zero status into 0. 1325 1326There is also ``$pipestatus``, which is a list of all ``status`` values of processes in a pipe. One difference is that :ref:`not <cmd-not>` applies to ``$status``, but not ``$pipestatus``, because it loses information. 1327 1328For example:: 1329 1330 not cat file | grep -q fish 1331 echo status is: $status pipestatus is $pipestatus 1332 1333Here ``$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. 1334 1335So if both ``cat`` and ``grep`` succeeded, ``$status`` would be 1 because of the ``not``, and ``$pipestatus`` would be 0 and 0. 1336 1337.. _variables-locale: 1338 1339Locale variables 1340^^^^^^^^^^^^^^^^ 1341 1342The "locale" of a program is its set of language and regional settings. In UNIX, there are a few separate variables to control separate things - ``LC_CTYPE`` defines the text encoding while ``LC_TIME`` defines the time format. 1343 1344The locale variables are: ``LANG``, ``LC_ALL``, ``LC_COLLATE``, ``LC_CTYPE``, ``LC_MESSAGES``, ``LC_MONETARY``, ``LC_NUMERIC`` and ``LC_TIME``. These variables work as follows: ``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 (this is typically not recommended!). 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. 1345 1346The most common way to set the locale to use a command like ``set -gx 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. That way any program that requires one setting differently can easily override just that and doesn't have to resort to LC_ALL. For a list of available locales on your system, try ``locale -a``. 1347 1348Because it needs to handle output that might include multibyte characters (like e.g. emojis), fish will try to set its own internal LC_CTYPE to one that is UTF8-capable even if given an effective LC_CTYPE of "C" (the default). This prevents issues with e.g. filenames given in autosuggestions even if the user started fish with LC_ALL=C. To turn this handling off, set ``fish_allow_singlebyte_locale`` to "1". 1349 1350.. _builtin-overview: 1351 1352Builtin commands 1353---------------- 1354 1355Fish includes a number of commands in the shell directly. We call these "builtins". These include: 1356 1357- Builtins that manipulate the shell state - :ref:`cd <cmd-cd>` changes directory, :ref:`set <cmd-set>` sets variables 1358- Builtins for dealing with data, like :ref:`string <cmd-string>` for strings and :ref:`math <cmd-math>` for numbers, :ref:`count <cmd-count>` for counting lines or arguments 1359- :ref:`status <cmd-status>` for asking about the shell's status 1360- :ref:`printf <cmd-printf>` and :ref:`echo <cmd-echo>` for creating output 1361- :ref:`test <cmd-test>` for checking conditions 1362- :ref:`argparse <cmd-argparse>` for parsing function arguments 1363- :ref:`source <cmd-source>` to read a script in the current shell (so changes to variables stay) and :ref:`eval <cmd-eval>` to execute a string as script 1364- :ref:`random <cmd-random>` to get random numbers or pick a random element from a list 1365 1366For a list of all builtins, use ``builtin -n``. 1367 1368For a list of all builtins, functions and commands shipped with fish, see the :ref:`list of commands <Commands>`. The documentation is also available by using the ``--help`` switch. 1369 1370.. _identifiers: 1371 1372Shell variable and function names 1373--------------------------------- 1374 1375The names given to variables and functions (so called "identifiers") have to follow certain rules: 1376 1377- A variable name cannot be empty. It can contain only letters, digits, and underscores. It may begin and end with any of those characters. 1378 1379- 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. 1380 1381- A bind mode name (e.g., ``bind -m abc ...``) must be a valid variable name. 1382 1383Other 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). 1384 1385.. _featureflags: 1386 1387Future feature flags 1388-------------------- 1389 1390Feature 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. 1391 1392You can see the current list of features via ``status features``:: 1393 1394 > status features 1395 stderr-nocaret on 3.0 ^ no longer redirects stderr 1396 qmark-noglob off 3.0 ? no longer globs 1397 regex-easyesc off 3.1 string replace -r needs fewer \\'s 1398 1399There are two breaking changes in fish 3.0: caret ``^`` no longer redirects stderr, and question mark ``?`` is no longer a glob. 1400 1401There is one breaking change in fish 3.1: ``string replace -r`` does a superfluous round of escaping for the replacement, so escaping backslashes would look like ``string replace -ra '([ab])' '\\\\\\\$1' a``. This flag removes that if turned on, so ``'\\\\$1'`` is enough. 1402 1403 1404These changes are off by default. They can be enabled on a per session basis:: 1405 1406 > fish --features qmark-noglob,stderr-nocaret 1407 1408 1409or opted into globally for a user:: 1410 1411 1412 > set -U fish_features stderr-nocaret qmark-noglob 1413 1414Features will only be set on startup, so this variable will only take effect if it is universal or exported. 1415 1416You can also use the version as a group, so ``3.0`` is equivalent to "stderr-nocaret" and "qmark-noglob". 1417 1418Prefixing a feature with ``no-`` turns it off instead. 1419 1420.. _event: 1421 1422Event handlers 1423-------------- 1424 1425When 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: 1426 1427- When a signal is delivered 1428- When a job exits 1429- When the value of a variable is updated 1430- When the prompt is about to be shown 1431 1432Example: 1433 1434To specify a signal handler for the WINCH signal, write:: 1435 1436 function my_signal_handler --on-signal WINCH 1437 echo Got WINCH signal! 1438 end 1439 1440Please note that event handlers only become active when a function is loaded, which means you need to otherwise :ref:`source <cmd-source>` or execute a function instead of relying on :ref:`autoloading <syntax-function-autoloading>`. One approach is to put it into your :ref:`configuration file <configuration>`. 1441 1442For more information on how to define new event handlers, see the documentation for the :ref:`function <cmd-function>` command. 1443 1444 1445.. _debugging: 1446 1447Debugging fish scripts 1448---------------------- 1449 1450Fish includes a built in debugging facility. The debugger allows you to stop execution of a script at an arbitrary point. When this happens you are presented with an interactive prompt. At this prompt you can execute any fish command (there are no debug commands as such). For example, you can check or change the value of any variables using :ref:`printf <cmd-printf>` and :ref:`set <cmd-set>`. As another example, you can run :ref:`status print-stack-trace <cmd-status>` to see how this breakpoint was reached. To resume normal execution of the script, simply type :ref:`exit <cmd-exit>` or :kbd:`Control`\ +\ :kbd:`D`. 1451 1452To start a debug session simply run the builtin command :ref:`breakpoint <cmd-breakpoint>` at the point in a function or script where you wish to gain control. Also, 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 with the ``kill`` command. Once in the debugger, it is easy to insert new breakpoints by using the funced function to edit the definition of a function. 1453