Fish export variable

Fish export variable DEFAULT

Is there a way to "source" a sh script from the fish shell?

I like to put many of my environment variable definitions in the script. If I am using a POSIX-compatible interactive shell like bash, I can use the source command to re-export the environment variables from when it gets updated, without needing to open a new terminal window. Is there a way to do the same when I am using , which uses a different syntax for exporting variables? Can I tell fish to run a subproccess and reexport any variables it defines?

When I try doing the obvious the environment variables apparently only get defined in the child process and don't get updated in the parent process.


edit: the shell code defining my variables is this one

Unfortunately, this code is automatically generated by another program, so the conversion to Fish must also be made using an automated process. I tried using the following sed script

which outputs the following Fish code

Which I can run using eval and substitution

However, fish is complaining when I try to set PATH. I think it might be special-casing PATH and expecting an array instead of a single string.

Sours: https://superuser.com/questions/826333/is-there-a-way-to-source-a-sh-script-from-the-fish-shell

Fish shell: variable with last argument

Fish shell variables

Introduction, If set is called with no arguments, the names and values of all shell variables are printed in sorted order. If some of the scope or export flags have been given,  Shell variables¶ Shell variables are named pieces of data, which can be created, deleted and their values changed and used by the user. Variables may optionally be "exported", so that a copy of the variable is available to any subprocesses the shell creates. An exported variable is referred to as an "environment variable".

set, Unlike other shells, fish has no dedicated VARIABLE=VALUE syntax for setting variables. Instead it has an ordinary command: set , which takes a variable name,​  For those lucky few with a graphical computer, you can set your colors and view functions, variables, and history all from a web page. Man Page Completions Other shells support programmable completions, but only fish generates them automatically by parsing your installed man pages.

Tutorial, How do I get the exit status of a command? Use the $status variable. This replaces the $? variable used in some other shells. Universal variables. Fish has a feature known as universal variables, which allow a user to permanently assign a value to a variable across all the user's running fish shells. The variable value is remembered across logouts and reboots, and updates are immediately propagated to all running shells.

Fish shell themes

It is easy to use, fast and extensible. Using omf, you can easily install themes that enriches the look of your shell and install plugins to tweak your fish shell as per your wish. Install Oh My Fish. Installing omf is not a big deal. All you have to do is just run the following command in your fish shell.

We would like to show you a description here but the site won’t allow us.

fish shell, version 2.2 or later; git, version 1.9.5 or later; Known Issues. Due to a regression bug in fish 2.6 with some terminal emulators, right prompts make the shell unusable. OMF's default theme features a right prompt, so it's necessary to use an

Fish-shell test

test, For compatibility with other shells, the second form is available: a matching pair of square brackets ( [ [EXPRESSION ] ] ). This test is mostly POSIX-compatible. line shell for the 90s fish is a smart and user-friendly command line shell for Linux, macOS, and the rest of the family.

Commands, Description¶. contains tests whether the set VALUES contains the string KEY . If so, contains exits with status 0; if not, it exits with status 1. The following options  The user-friendly command line shell. Contribute to fish-shell/fish-shell development by creating an account on GitHub.

contains, fish ships with a large number of builtin commands, shellscript functions and This way it becomes significantly easier to test the function while editing, and the​  Fish will suggest file names and commands as you type them. For instance, if you would like to edit the file in your home directory called test.txt, you can type nano ~/te, and Fish will preview the rest of the filename. Press the RIGHT arrow key to accept the suggestion. Fish offers more complete suggestions than Bash because it indexes the

Fish shell alias

alias, It has similar syntax to POSIX shell alias . For other uses, it is recommended to define a function. fish marks functions that have been created by alias  I would like to define some aliases in fish. Apparently it should be possible to define them in ~/.config/fish/functions but they don't get auto loaded when I restart the shell.

Commands, Edit the fish configuration. $ vim ~/.config/fish/config.fish. Basic usage alias `​command` = `your command`. For example alias g='git'. Use the  abbr - manage fish abbreviations; alias - create a function; and - conditionally execute a command; argparse - parse options passed to a fish script or function

How to make an alias in Fish Shell | by Chen-I Chang, Just use alias . Here's a basic example: # Define alias in shell alias rmi "rm -i" # Define alias in config file alias rmi="rm -i" # This is equivalent to  Fish-Shell Will Not Save my Aliases. Ask Question Asked 4 years, 2 months ago. Active 2 years, 10 months ago. Viewed 7k times 8. 2. I do not know why, but after

Fish shell shortcuts

Introduction, Command reference. fish ships with a large number of builtin commands, shellscript functions and external commands. These are all described below. Almost all  The one-page guide to Fish shell: usage, examples, links, snippets, and more.

Commands, Shortcut, Description. Alt ← / Alt →, Move word. ^U, Delete to beginning. ^W, Delete to previous /. ^D, Delete next character. Alt D, Delete next word. ^C, Cancel  The fish shell is running the clear command, which now makes use of this terminfo augmentation. The name given in the value of your TERM environment variable must match the name of a termcap/terminfo record that correctly describes your terminal emulator's operation.

fish shell Cheat Sheet by myounkin, Fish has no support for !!, but you can use the Oh My Fish Shell framework and install thebang-bang plugin to have this shortcut in the fish Shell. Slower than Bash Most of the fish

Fish shell vs zsh

Why I Switched from ZSH to FISH, Unix Shell is a powerful tool that allows programmers to accomplish complex tasks with just a few words. There are a lot of widely available Shells  The fish community maintains Oh My Fish, which is a shell framework inspired by Oh My Zsh. It offers a lot of beautiful prompt themes and awesome plugins, is lightweight, awesome, and easy to use.

Fish vs. Zsh vs. Bash and Why You Should Switch to Fish, This is what I believe the fish shell has become. No wasted time scouring the web for config files others have shared, the best plugins to use, or  Bash vs Zsh vs Fish 6th May 2020. When I set up my Windows computer, I had the chance to take another look at the shell I’m using. The three main ones out there are Bash, Zsh, and Fish. I knew of Bash. I used Zsh previously. But how would Fish fare? I’ve heard great things about it, so I tried it out.

Why I Use Fish Shell Over Bash and Zsh | by Alec Brunelle, Bash vs Zsh vs Fish. 6th May 2020. When I set up my Windows computer, I had the chance to take another look at the shell I'm using. The three main ones out  Fish community maintains Oh My Fish, which is a shell framework inspired on Oh My Zsh awesome design and name. It offer a lot of beautiful prompt themes and awesome plugins, is lightweight, awesome and very simple to use.

Fish shell history

shell for Linux, macOS, and the rest of the family. Autosuggestions fish suggests commands as you type based on history and completions, just like a web browser.

where is the history file location? can it be customized? can fish use as starting point the zsh history file? does it merge all terminal sessions into 1 big history file? (seems so) suggestion: up/down searches in global history (starti

The friendly interactive shell (fish) is a Unix shell that attempts to be more interactive and user-friendly than those with a longer history (i.e. most other Unix shells) or those formulated as function-compatible replacements for the aforementioned (e.g. zsh, the Falstad shell).

Fish-shell key bindings

bind, The default key binding can be set by specifying a SEQUENCE of the empty string (that is, '' ). It will be used whenever no other binding matches. For most key bindings, it makes sense to use the self-insert function (i.e. bind '' self-insert ) as the default keybinding. Note that Alt-based key bindings are case sensitive and Control-based key bindings are not. This is a constraint of text-based terminals, not fish. The default key binding can be set by specifying a SEQUENCE of the empty string (that is, ''). It will be used whenever no other binding matches.

Introduction, Hi, I am currently trying to increase my productivity with fish shell by learning some keybindings. However I can't find any documentation for the  Contribute to fish-shell/fish-shell development by creating an account on GitHub. function fish_default_key_bindings-d " Default (Emacs-like) key bindings for fish "

Documentation for keybindings? · Issue #4086 · fish-shell/fish-shell , I am new to fish(just switch from bash this morning) and I want to use Ctrl + L to clear my screen. So I added  fish_key_reader - explore what characters keyboard keys send fish_mode_prompt - define the appearance of the mode indicator fish_opt - create an option spec for the argparse command


The answers/references are collected from stacksoverflow, are licensed under Creative Commons Attribution-ShareAlike license.

Sours: http://coddingbuddy.com/article/58053189/fish-shell-variable-with-last-argument
  1. Lovely closet boutique
  2. Bodyguard name generator
  3. Evil fish drawings
  4. Craigslist fredericksburg
  5. Craftsman industrial tools catalog

Tutorial¶

Why fish?¶

Fish is a fully-equipped command line shell (like bash or zsh) that is smart and user-friendly. Fish supports powerful features like syntax highlighting, autosuggestions, and tab completions that just work, with nothing to learn or configure.

If you want to make your command line more productive, more useful, and more fun, without learning a bunch of arcane syntax and configuration options, then fish might be just what you're looking for!

Getting started¶

Once installed, just type in into your current shell to try it out!

You will be greeted by the standard fish prompt, which means you are all set up and can start using fish:

> fish Welcome to fish, the friendly interactive shell Type help for instructions on how to use fish [email protected] ~>

This prompt that you see above is the fish default prompt: it shows your username, hostname, and working directory. - to change this prompt see how to change your prompt - to switch to fish permanently see switch your default shell to fish.

From now on, we'll pretend your prompt is just a to save space.

Learning fish¶

This tutorial assumes a basic understanding of command line shells and Unix commands, and that you have a working copy of fish.

If you have a strong understanding of other shells, and want to know what fish does differently, search for the magic phrase unlike other shells, which is used to call out important differences.

Or, if you want a quick overview over the differences to other shells like Bash, see Fish For Bash Users.

Running Commands¶

Fish runs commands like other shells: you type a command, followed by its arguments. Spaces are separators:

> echohelloworld hello world

This runs the command with the arguments and . In this case that's the same as one argument , but in many cases it's not. If you need to pass an argument that includes a space, you can escape with a backslash, or quote it using single or double quotes:

> mkdirMy\ Files # Makes a directory called "My Files", with a space in the name > cp~/Some\ File'My Files' # Copies a file called "Some File" in the home directory to "My Files" > ls"My Files" Some File

Getting Help¶

Run to open fish's help in a web browser, and with the page (like ) to open it in a man page. You can also ask for help with a specific command, for example, to open in a web browser, or to see it in the terminal.

> manset set - handle shell variables Synopsis...

Syntax Highlighting¶

You'll quickly notice that fish performs syntax highlighting as you type. Invalid commands are colored red by default:

>/bin/mkd

A command may be invalid because it does not exist, or refers to a file that you cannot execute. When the command becomes valid, it is shown in a different color:

Valid file paths are underlined as you type them:

>cat~/somefi

This tells you that there exists a file that starts with , which is useful feedback as you type.

These colors, and many more, can be changed by running , or by modifying color variables directly.

Wildcards¶

Fish supports the familiar wildcard . To list all JPEG files:

> ls*.jpg lena.jpg meena.jpg santa maria.jpg

You can include multiple wildcards:

> lsl*.p* lena.png lesson.pdf

Especially powerful is the recursive wildcard ** which searches directories recursively:

> ls/var/**.log /var/log/system.log /var/run/sntp.log

If that directory traversal is taking a long time, you can + out of it.

For more, see Wildcards.

Pipes and Redirections¶

You can pipe between commands with the usual vertical bar:

> echohelloworld|wc 1 2 12

stdin and stdout can be redirected via the familiar and . stderr is redirected with a .

> grepfish</etc/shells>~/output.txt2>~/errors.txt

To redirect stdout and stderr into one file, you need to first redirect stdout, and then stderr into stdout:

> make>make_output.txt2>&1

For more, see Input and output redirections and Pipes.

Autosuggestions¶

As you type fish will suggest commands to the right of the cursor, in gray. For example:

>/bin/hostname

It knows about paths and options:

>grep--ignore-case

And history too. Type a command once, and you can re-summon it by just typing a few letters:

>rsync -avze ssh . myname@somelonghost.com:/some/long/path/doo/dee/doo/dee/doo

To accept the autosuggestion, hit (right arrow) or +. To accept a single word of the autosuggestion, + (right arrow). If the autosuggestion is not what you want, just ignore it.

Tab Completions¶

A rich set of tab completions work "out of the box".

Press and fish will attempt to complete the command, argument, or path:

>/pri => /private/

If there's more than one possibility, it will list them:

>~/stuff/s ~/stuff/script.sh (Executable, 4.8kB) ~/stuff/sources/ (Directory)

Hit tab again to cycle through the possibilities.

fish can also complete many commands, like git branches:

>gitmerge pr => gitmerge prompt_designer>gitcheckout b builtin_list_io_merge (Branch) builtin_set_color (Branch) busted_events (Tag)

Try hitting tab and see what fish can do!

Variables¶

Like other shells, a dollar sign followed by a variable name is replaced with the value of that variable:

> echoMyhomedirectoryis$HOME My home directory is /home/tutorial

This is known as variable substitution, and it also happens in double quotes, but not single quotes:

> echo"My current directory is $PWD" My current directory is /home/tutorial > echo'My current directory is $PWD' My current directory is $PWD

Unlike other shells, fish has no dedicated syntax for setting variables. Instead it has an ordinary command: , which takes a variable name, and then its value.

> setname'Mister Noodle'> echo$name Mister Noodle

(Notice the quotes: without them, and would have been separate arguments, and would have been made into a list of two elements.)

Unlike other shells, variables are not further split after substitution:

> mkdir$name> ls Mister Noodle

In bash, this would have created two directories "Mister" and "Noodle". In fish, it created only one: the variable had the value "Mister Noodle", so that is the argument that was passed to , spaces and all. Other shells use the term "arrays", rather than lists.

You can erase (or "delete") a variable with or

> set-eMyVariable> env|grepMyVariable (no output)

For more, see Variable expansion.

Exports (Shell Variables)¶

Sometimes you need to have a variable available to an external command, often as a setting. For example many programs like or read the variable to figure out your preferred pager (the program that lets you scroll text). Other variables used like this include , (to configure your language) and . You'll note these are written in ALLCAPS, but that's just a convention.

To give a variable to an external command, it needs to be "exported". Unlike other shells, fish does not have an export command. Instead, a variable is exported via an option to , either or just .

> set-xMyVariableSomeValue> env|grepMyVariable MyVariable=SomeValue

It can also be unexported with or .

This works the other way around as well! If fish is started by something else, it inherits that parents exported variables. So if your terminal emulator starts fish, and it exports set to , fish will receive that setting. And whatever started your terminal emulator also gave it some variables that it will then pass on unless it specifically decides not to. This is how fish usually receives the values for things like , and , without you having to specify them again.

Exported variables can be local or global or universal - "exported" is not a scope! Usually you'd make them global via .

For more, see Exporting variables.

Lists¶

The command above used quotes to ensure that was one argument. If it had been two arguments, then would have been a list of length 2. In fact, all variables in fish are really lists, that can contain any number of values, or none at all.

Some variables, like , only have one value. By convention, we talk about that variable's value, but we really mean its first (and only) value.

Other variables, like , really do have multiple values. During variable expansion, the variable expands to become multiple arguments:

> echo$PATH /usr/bin /bin /usr/sbin /sbin /usr/local/bin

Variables whose name ends in "PATH" are automatically split on colons to become lists. They are joined using colons when exported to subcommands. This is for compatibility with other tools, which expect $PATH to use colons. You can also explicitly add this quirk to a variable with , or remove it with .

Lists cannot contain other lists: there is no recursion. A variable is a list of strings, full stop.

Get the length of a list with :

You can append (or prepend) to a list by setting the list to itself, with some additional arguments. Here we append /usr/local/bin to $PATH:

> setPATH$PATH/usr/local/bin

You can access individual elements with square brackets. Indexing starts at 1 from the beginning, and -1 from the end:

> echo$PATH /usr/bin /bin /usr/sbin /sbin /usr/local/bin > echo$PATH[1] /usr/bin > echo$PATH[-1] /usr/local/bin

You can also access ranges of elements, known as "slices":

> echo$PATH[1..2] /usr/bin /bin > echo$PATH[-1..2] /usr/local/bin /sbin /usr/sbin /bin

You can iterate over a list (or a slice) with a for loop:

> forvalin$PATH echo "entry: $val" end entry: /usr/bin/ entry: /bin entry: /usr/sbin entry: /sbin entry: /usr/local/bin

Lists adjacent to other lists or strings are expanded as cartesian products unless quoted (see Variable expansion):

> seta123> set1abc> echo$a$1 1a 2a 3a 1b 2b 3b 1c 2c 3c > echo$a" banana" 1 banana 2 banana 3 banana > echo"$a banana" 1 2 3 banana

This is similar to Brace expansion.

For more, see Lists.

Command Substitutions¶

Command substitutions use the output of one command as an argument to another. Unlike other shells, fish does not use backticks `` for command substitutions. Instead, it uses parentheses:

> echoIn(pwd),running(uname) In /home/tutorial, running FreeBSD

A common idiom is to capture the output of a command in a variable:

> setos(uname)> echo$os Linux

Command substitutions are not expanded within quotes. Instead, you can temporarily close the quotes, add the command substitution, and reopen them, all in the same argument:

> touch"testing_"(date+%s)".txt"> ls*.txt testing_1360099791.txt

Unlike other shells, fish does not split command substitutions on any whitespace (like spaces or tabs), only newlines. This can be an issue with commands like that print what is meant to be multiple arguments on a single line. To split it on spaces too, use .

> printf'%s\n'(pkg-config--libsgio-2.0) -lgio-2.0 -lgobject-2.0 -lglib-2.0 > printf'%s\n'(pkg-config--libsgio-2.0|stringsplit-n" ") -lgio-2.0 -lgobject-2.0 -lglib-2.0

If you need a command substitutions output as one argument, without any splits, use :

> echo"first line second line" > myfile > setmyfile(catmyfile|stringcollect)> printf'|%s|'$myfile |first line second line|

For more, see Command substitution.

Separating Commands (Semicolon)¶

Like other shells, fish allows multiple commands either on separate lines or the same line.

To write them on the same line, use the semicolon (";"). That means the following two examples are equivalent:

echofish;echochips# orechofishechochips

Exit Status¶

When a command exits, it returns a status code as a non-negative integer.

Unlike other shells, fish stores the exit status of the last command in instead of .

> false> echo$status 1

This indicates how the command fared - 0 usually means success, while the others signify kinds of failure. For instance fish's returns the number of variables it queried that weren't set - usually returns 0, usually returns 2.

There is also a list variable for the exit statuses 1 of processes in a pipe.

For more, see The status variable.

Combiners (And, Or, Not)¶

fish supports the familiar and to combine commands, and to negate them:

> ./configure&&make&&sudomakeinstall

Here, is only executed if succeeds (returns 0), and is only executed if both and succeed.

fish also supports and, or, and not. The first two are job modifiers and have lower precedence. Example usage:

> cpfile1file1_bak&&cpfile2file2_bak;andecho"Backup successful";orecho"Backup failed" Backup failed

As mentioned in the section on the semicolon, this can also be written in multiple lines, like so:

cpfile1file1_bak&&cpfile2file2_bakandecho"Backup successful"orecho"Backup failed"

Conditionals (If, Else, Switch)¶

Use if and else to conditionally execute code, based on the exit status of a command.

ifgrepfish/etc/shellsechoFoundfishelseifgrepbash/etc/shellsechoFoundbashelseechoGotnothingend

To compare strings or numbers or check file properties (whether a file exists or is writeable and such), use test, like

iftest"$fish"="flounder"echoFLOUNDERend# oriftest"$number"-gt5echo$numberisgreaterthanfiveelseecho$numberisfiveorlessend# or# This test is true if the path /etc/hosts exists# - it could be a file or directory or symlink (or possibly something else).iftest-e/etc/hostsechoWemostlikelyhaveahostsfileelseechoWedonothaveahostsfileend

Combiners can also be used to make more complex conditions, like

ifgrepfish/etc/shells;andcommand-sqfishechofishisinstalledandconfiguredend

For even more complex conditions, use begin and end to group parts of them.

There is also a switch command:

switch(uname)caseLinuxechoHiTux!caseDarwinechoHiHexley!caseFreeBSDNetBSDDragonFlyechoHiBeastie!case'*'echoHi,stranger!end

As you see, case does not fall through, and can accept multiple arguments or (quoted) wildcards.

For more, see Conditions.

Functions¶

A fish function is a list of commands, which may optionally take arguments. Unlike other shells, arguments are not passed in "numbered variables" like , but instead in a single list . To create a function, use the function builtin:

> functionsay_hello echo Hello $argv end > say_hello Hello > say_helloeverybody! Hello everybody!

Unlike other shells, fish does not have aliases or special prompt syntax. Functions take their place. 2

You can list the names of all functions with the functions builtin (note the plural!). fish starts out with a number of functions:

> functions N_, abbr, alias, bg, cd, cdh, contains_seq, delete-or-exit, dirh, dirs, disown, down-or-search, edit_command_buffer, export, fg, fish_add_path, fish_breakpoint_prompt, fish_clipboard_copy, fish_clipboard_paste, fish_config, fish_default_key_bindings, fish_default_mode_prompt, fish_git_prompt, fish_hg_prompt, fish_hybrid_key_bindings, fish_indent, fish_is_root_user, fish_job_summary, fish_key_reader, fish_md5, fish_mode_prompt, fish_npm_helper, fish_opt, fish_print_git_action, fish_print_hg_root, fish_prompt, fish_sigtrap_handler, fish_svn_prompt, fish_title, fish_update_completions, fish_vcs_prompt, fish_vi_cursor, fish_vi_key_bindings, funced, funcsave, grep, help, history, hostname, isatty, kill, la, ll, ls, man, nextd, nextd-or-forward-word, open, popd, prevd, prevd-or-backward-word, prompt_hostname, prompt_pwd, psub, pushd, realpath, seq, setenv, suspend, trap, type, umask, up-or-search, vared, wait

You can see the source for any function by passing its name to :

> functionsls function ls --description 'List contents of directory' command ls -G $argv end

For more, see Functions.

Loops¶

While loops:

> whiletrue echo "Loop forever" end Loop forever Loop forever Loop forever ... # yes, this really will loop forever. Unless you abort it with ctrl-c.

For loops can be used to iterate over a list. For example, a list of files:

> forfilein*.txt cp $file $file.bak end

Iterating over a list of numbers can be done with :

> forxin(seq5) touch file_$x.txt end

For more, see Loops and blocks.

Prompt¶

Unlike other shells, there is no prompt variable like . To display your prompt, fish executes the fish_prompt function and uses its output as the prompt. And if it exists, fish also executes the fish_right_prompt function and uses its output as the right prompt.

You can define your own prompt from the command line:

> functionfish_prompt;echo"New Prompt % ";end New Prompt % _

Then, if you are happy with it, you can save it to disk by typing . This saves the prompt in . (Or, if you want, you can create that file manually from the start.)

Multiple lines are OK. Colors can be set via set_color, passing it named ANSI colors, or hex RGB values:

functionfish_promptset_colorpurpledate"+%m/%d/%y"set_colorF00echo(pwd)'>'(set_colornormal)end

This prompt would look like:

02/06/13/home/tutorial > _

You can choose among some sample prompts by running for a web UI or for a simpler version inside your terminal.

$PATH¶

is an environment variable containing the directories that fish searches for commands. Unlike other shells, $PATH is a list, not a colon-delimited string.

Fish takes care to set to a default, but typically it is just inherited from fish's parent process and is set to a value that makes sense for the system - see Exports.

To prepend /usr/local/bin and /usr/sbin to , you can write:

> setPATH/usr/local/bin/usr/sbin$PATH

To remove /usr/local/bin from , you can write:

> setPATH(stringmatch-v/usr/local/bin$PATH)

For compatibility with other shells and external commands, $PATH is a path variable, and so will be joined with colons (not spaces) when you quote it:

> echo"$PATH" /usr/local/sbin:/usr/local/bin:/usr/bin

and it will be exported like that, and when fish starts it splits the $PATH it receives into a list on colon.

You can do so directly in , like you might do in other shells with . See this example.

A faster way is to use the fish_add_path function, which adds given directories to the path if they aren't already included. It does this by modifying the universal variable, which is automatically prepended to . For example, to permanently add to your , you could write:

> fish_add_path/usr/local/bin

The advantage is that you don't have to go mucking around in files: just run this once at the command line, and it will affect the current session and all future instances too. You can also add this line to config.fish, as it only adds the component if necessary.

Or you can modify $fish_user_paths yourself, but you should be careful not to append to it unconditionally in config.fish, or it will grow longer and longer.

Startup (Where's .bashrc?)¶

Fish starts by executing commands in . You can create it if it does not exist.

It is possible to directly create functions and variables in file, using the commands shown above. For example:

> cat~/.config/fish/config.fish set -x PATH $PATH /sbin/ function ll ls -lh $argv end

However, it is more common and efficient to use autoloading functions and universal variables.

If you want to organize your configuration, fish also reads commands in .fish files in . See Configuration Files for the details.

Autoloading Functions¶

When fish encounters a command, it attempts to autoload a function for that command, by looking for a file with the name of that command in .

For example, if you wanted to have a function , you would add a text file to :

> cat~/.config/fish/functions/ll.fish function ll ls -lh $argv end

This is the preferred way to define your prompt as well:

> cat~/.config/fish/functions/fish_prompt.fish function fish_prompt echo (pwd) "> " end

See the documentation for funced and funcsave for ways to create these files automatically, and $fish_function_path to control their location.

Universal Variables¶

A universal variable is a variable whose value is shared across all instances of fish, now and in the future – even after a reboot. You can make a variable universal with :

Now in another shell:

Switching to fish?¶

If you wish to use fish (or any other shell) as your default shell, you need to enter your new shell's executable in two places.

Add the shell to with:

> echo/usr/local/bin/fish|sudotee-a/etc/shells

Change your default shell with:

> chsh-s/usr/local/bin/fish

This assumes you installed fish to /usr/local/bin, which is the default location when you've compiled it yourself. If you installed it with a package manager, the usual location is /usr/bin/fish, but package managers typically already add it to /etc/shells. Just substitute the correct location.

(To change it back to another shell, just substitute with , or as appropriate in the steps above.)

Sours: https://fishshell.com/docs/current/tutorial.html
Amazing Automatic Fish Processing Line Machines Modern Technology - Big Catch in The Sea

Setting exports in Fish Shell

I have multiple versions of PHP installed, and for my normal development I always use PHP 5.5.x installed via homebrew.

In the fish shell

The path is correct.

My problem is that when I have to develop with Drupal I use MAMP as a bundled lamp stack, and MAMP has its own php version included. My problem is that when using Drush with Drupal I cannot set the PHP executable path as I normally would in bash. I only want drush to use the bundled PHP version/executable.

In bash I can do this:

But this wont work in fish-shell, I tried with this (no success):

fish config location:

If I run the fishshell with i always get this:

And when I run the same command in bourne shell I get the correct settings:

So, how to set the export path to the DRUSH_PHP in fish?

asked Feb 7 '14 at 9:56

patpat

5,21133 gold badges2323 silver badges3030 bronze badges

Sours: https://stackoverflow.com/questions/21624512/setting-exports-in-fish-shell

Variable fish export

fish

Related articles

fish, the friendly interactive shell, is a commandline shell intended to be interactive and user-friendly.

fish is intentionally not fully POSIX compliant, it aims at addressing POSIX inconsistencies (as perceived by the creators) with a simplified or a different syntax. This means that even simple POSIX compliant scripts may require some significant adaptation or even full rewriting to run with fish.

Installation

Install the fish package. For the development version, install the fish-gitAUR package.

Once installed, simply type to drop into the fish shell.

Documentation can be found by typing from fish; it will be opened in a web browser. It is recommended to read at least the "Syntax overview" section, since fish's syntax is different from many other shells.

System integration

One must decide whether fish is going to be the default user's shell, which means that the user falls directly in fish at login, or whether it is used in interactive terminal mode as a child process of the current default shell, here we will assume the latter is Bash. To elaborate on these two setups:

  • fish used as the default shell: this mode requires some basic understanding of the fish functioning and its scripting language. The user's current initialization scripts and environment variables need to be migrated to the new fish environment. To configure the system in this mode, follow #Setting fish as default shell.
  • fish used as an interactive shell only: this is the less disruptive mode, all the Bash initialization scripts are run as usual and fish runs on top of Bash in interactive mode connected to a terminal. To setup fish in this mode, follow #Setting fish as interactive shell only.

Setting fish as default shell

If you decide to set fish as the default user shell, the first step is to set the shell of this particular user to . This can be done by following the instructions in Command-line shell#Changing your default shell.

The next step is to port the current needed actions and configuration performed in the various Bash initialization scripts, namely , , and , into the fish framework.

In particular, the content of the environment variable, once directly logged under fish, should be checked and adjusted to one's need. In fish, is defined as a global environment variable: it has a global scope across all functions, it is lost upon reboot and it is an environment variable which means it is exported to child processes. The recommended way of adding additional locations to the path is by calling the fish_add_path command from . For example:

$ fish_add_path -p /first/path/second/path/third/one

These three locations will be prepended to the path.

Setting fish as interactive shell only

Not setting fish as system wide or user default allows the current Bash scripts to run on startup. It ensures the current user's environment variables are unchanged and are exported to fish which then runs as a Bash child. Below are several ways of running fish in interactive mode without setting it as the default shell.

Modify .bashrc to drop into fish

Keep the default shell as Bash and simply add the line to the appropriate Bash#Configuration files, such as . This will allow Bash to properly source and all files in . Because fish replaces the Bash process, exiting fish will also exit the terminal. Compared to the following options, this is the most universal solution, since it works both on a local machine and on a SSH server.

Tip:
  • In this setup, use to manually enter Bash without executing the commands from which would run and drop back into fish.
  • To have commands such as run the command in Bash instead of starting fish, you can write instead.
  • Drop in to fish only if the parent process is not fish. This allows to quickly enter in to bash by invoking command without losing configuration: if [[ $(ps --no-header --pid=$PPID --format=cmd) != "fish" && -z ${BASH_EXECUTION_STRING} ]] then exec fish fi

Use terminal emulator options

Another option is to open your terminal emulator with a command line option that executes fish. For most terminals this is the switch, so for example, to open gnome-terminal using fish, change your shortcut to use:

gnome-terminal -e fish

With terminal emulators that do not support setting the shell, for example lilyterm-gitAUR, it would look like this:

SHELL=/usr/bin/fish lilyterm

Also, depending on the terminal, you may be able to set fish as the default shell in either the terminal configuration or the terminal profile.

Use terminal multiplexer options

To set fish as the shell started in tmux, put this into your :

set-option -g default-shell "/usr/bin/fish"

Whenever you run tmux, you will be dropped into fish.

Configuration

The configuration file runs at every login and is located at . Adding commands or functions to the file will execute/define them when opening a terminal, similar to . Note that whenever a variable needs to be preserved, it should be set as universal rather than defined in the aforementioned configuration file.

The user's functions are located in the directory under the filenames .

Web interface

The fish terminal colors, prompt, functions, variables, history, bindings and abbreviations can be set with the interactive web interface:

fish_config

It may fail to start if IPv6 has been disabled. See [1] and IPv6#Disable IPv6.

Command completion

fish can generate autocompletions from man pages. Completions are written to and can be generated by calling:

fish_update_completions

You can also define your own completions in . See for a few examples.

Context-aware completions for Arch Linux-specific commands like pacman, pacman-key, makepkg, pbget, pacmatic are built into fish, since the policy of the fish development is to include all the existent completions in the upstream tarball. The memory management is clever enough to avoid any negative impact on resources.

Tips and tricks

Command substitution

fish does not implement Bash style history substitution (e.g. ), and the developers recommend in the fish faq to use the interactive history recall interface instead: the arrow recalls whole past lines and (or ) recalls individual arguments, while prepends to the existing line.

However some workarounds are described in the fish wiki: while not providing complete history substitution, some functions replace with the previous command or with the previous last argument.

Command chaining

Command chaining and is not implemented in versions older than 3.0 and the recommended syntax to achieve similar results in fish is respectively and . Some keybindings can be set for automatic substitution as described in the fish wiki.

Disable greeting

By default, fish prints a greeting message at startup. To disable it, run once:

$ set -U fish_greeting

This clears the universal variable, shared with all fish instances and which is preserved upon restart of the shell.

Make su launch fish

If su starts with Bash because Bash is the target user's (root if no username is provided) default shell, one can define a function to redirect it to fish whatever the user's shell:

~/.config/fish/functions/su.fishfunction su command su --shell=/usr/bin/fish $argv end

Start X at login

Add the following to the bottom of your .

# Start X at login if status is-login if test -z "$DISPLAY" -a "$XDG_VTNR" = 1 exec startx -- -keeptty end end

For those running fish in interactive mode, replace with in the above code.

Put git status in prompt

If you would like fish to display the branch and dirty status when you are in a git directory, you can define the following function:

~/.config/fish/functions/fish_prompt.fish

However, this is now deprecated, see fish-shell git. Alternatively, the Informative Git Prompt has now been built into fish and can be activated from fish_config if so desired.

Color the hostname in the prompt in SSH

To color the hostname in the prompt dynamically whenever connected through SSH, add the following lines in either the function or the fish configuration file, here using the red color:

~/.config/fish/functions/fish_prompt.fish... if set -q SSH_TTY set -g fish_color_host brred end ...

Evaluate ssh-agent

In fish, generate errors due to how variables are set. To work around this, use the csh-style option :

$ eval (ssh-agent -c)

The "command not found" hook

Fish includes a "command not found" hook that will automatically search the official repositories, when entering an unrecognized command. This hook will be run using pkgfile, falling back to if it is not installed.

Since 3.2.2, "command not found" will not fallback to by default due to its bad performance.

If the delay this behavior introduces is undesirable, this hook can be overridden by redefining so that it only prints an error message:

$ function fish_command_not_found __fish_default_command_not_found_handler $argv[1] end

To make this change permanent, the built-in can be used:

$ funcsave fish_command_not_found

Remove a process from the list of jobs

fish terminates any jobs put into the background when fish terminates. To keep a job running after fish terminates, first use the builtin. For example, the following starts in the background and then disowns it:

$ firefox & $ disown

This means firefox will not be closed when the fish process is closed. See disown(1) in fish for more details.

Set a persistent alias

To quickly make a persistent alias, one can simply use the method showed in this example:

$ alias lsl "ls -l" $ funcsave lsl

alias supports the / option since fish version 3.0:

$ alias -s lsl "ls -l"

This will create the function:

function lsl ls -l $argv end

and will set the alias as a persistent shell function. To see all functions and/or edit them, one can simply use and look into the Function tab in the web configuration page.

For more detailed information, see alias - create a function — fish-shell.

Faster filesystem navigation with zoxide

zoxide is a smarter cd command that lets you navigate anywhere in just a few keystrokes. It remembers your frequently used directories and uses a scoring mechanism to guess where you want to go.

See also

Sours: https://wiki.archlinux.org/title/Fish
How to fish export data export fish from India to other country

fish tutorial

is a fully-equipped command line shell (like bash or zsh) that is smart and user-friendly. supports powerful features like syntax highlighting, autosuggestions, and tab completions that just work, with nothing to learn or configure.

If you want to make your command line more productive, more useful, and more fun, without learning a bunch of arcane syntax and configuration options, then might be just what you're looking for!

This tutorial assumes a basic understanding of command line shells and Unix commands, and that you have a working copy of .

If you have a strong understanding of other shells, and want to know what does differently, search for the magic phrase unlike other shells, which is used to call out important differences.

When you start , you should see this:

Welcome to fish, the friendly interactive shellType help for instructions on how to use fish [email protected] ~>

comes with a default prompt that shows your username, hostname, and working directory. You'll see how to change your prompt further down. From now on, we'll pretend your prompt is just a '' to save space.

runs commands like other shells: you type a command, followed by its arguments. Spaces are separators:

>echohelloworldhello world

You can include a literal space in an argument with a backslash, or by using single or double quotes:

>mkdirMy\ Files>cp~/Some\ File'My Files'>ls"My Files"Some File

Commands can be chained with semicolons.

has excellent help and man pages. Run to open help in a web browser, and to open it in a man page. You can also ask for help with a specific command, for example, to open in a web browser, or to see it in the terminal.

>mansetset - handle shell variables Synopsis...

You'll quickly notice that performs syntax highlighting as you type. Invalid commands are colored red by default:

>/bin/mkd

A command may be invalid because it does not exist, or refers to a file that you cannot execute. When the command becomes valid, it is shown in a different color:

>/bin/mkdir

will underline valid file paths as you type them:

>cat~/somefi

This tells you that there exists a file that starts with '', which is useful feedback as you type.

These colors, and many more, can be changed by running , or by modifying variables directly.

supports the familiar wildcard . To list all JPEG files:

>ls*.jpglena.jpgmeena.jpgsanta maria.jpg

You can include multiple wildcards:

>lsl*.p*lena.pnglesson.pdf

Especially powerful is the recursive wildcard ** which searches directories recursively:

>ls/var/**.log/var/log/system.log/var/run/sntp.log

If that directory traversal is taking a long time, you can Control-C out of it.

You can pipe between commands with the usual vertical bar:

>echohelloworld|wc 1 2 12

stdin and stdout can be redirected via the familiar < and >. Unlike other shells, stderr is redirected with a caret ^

>grepfish< /etc/shells> ~/output.txt^ ~/errors.txt

suggests commands as you type, and shows the suggestion to the right of the cursor, in gray. For example:

>/bin/hostname

It knows about paths and options:

>grep--ignore-case

And history too. Type a command once, and you can re-summon it by just typing a few letters:

>rsync -avze ssh . [email protected]:/some/long/path/doo/dee/doo/dee/doo

To accept the autosuggestion, hit or Control-F. To accept a single word of the autosuggestion, Alt- (right arrow). If the autosuggestion is not what you want, just ignore it.

comes with a rich set of tab completions, that work "out of the box."

Press Tab, and will attempt to complete the command, argument, or path:

>/[email protected]{Tab} → /private/

If there's more than one possibility, it will list them:

>~/stuff/[email protected]{Tab} ~/stuff/script.sh (Executable, 4.8kB)~/stuff/sources/ (Directory)

Hit tab again to cycle through the possibilities.

can also complete many commands, like git branches:

>[email protected]{Tab} → gitmergeprompt_designer>[email protected]{Tab} builtin_list_io_merge (Branch)builtin_set_color (Branch)busted_events (Tag)

Try hitting tab and see what can do!

Like other shells, a dollar sign performs variable substitution:

>echoMyhomedirectoryis$HOMEMy home directory is /home/tutorial

Variable substitution also occurs in double quotes, but not single quotes:

>echo"My current directory is $PWD"My current directory is /home/tutorial>echo'My current directory is $PWD'My current directory is $PWD

Unlike other shells, has no dedicated syntax for setting variables. Instead it has an ordinary command: , which takes a variable name, and then its value.

>setname'Mister Noodle'>echo$nameMister Noodle

(Notice the quotes: without them, and would have been separate arguments, and would have been made into a list of two elements.)

Unlike other shells, variables are not further split after substitution:

>mkdir$name>lsMister Noodle

In bash, this would have created two directories "Mister" and "Noodle". In , it created only one: the variable had the value "Mister Noodle", so that is the argument that was passed to , spaces and all. Other shells use the term "arrays", rather than lists.

Unlike other shells, stores the exit status of the last command in instead of .

>false>echo$status1

Zero is considered success, and non-zero is failure.

Unlike other shells, does not have an export command. Instead, a variable is exported via an option to , either or just .

>set-xMyVariableSomeValue>env|grepMyVariableMyVariable=SomeValue

You can erase a variable with or

>set-eMyVariable>env|grepMyVariable(no output)

The command above used quotes to ensure that was one argument. If it had been two arguments, then would have been a list of length 2. In fact, all variables in are really lists, that can contain any number of values, or none at all.

Some variables, like , only have one value. By convention, we talk about that variable's value, but we really mean its first (and only) value.

Other variables, like , really do have multiple values. During variable expansion, the variable expands to become multiple arguments:

>echo$PATH/usr/bin /bin /usr/sbin /sbin /usr/local/bin

Lists cannot contain other lists: there is no recursion. A variable is a list of strings, full stop.

Get the length of a list with :

>count$PATH5

You can append (or prepend) to a list by setting the list to itself, with some additional arguments. Here we append /usr/local/bin to $PATH:

>setPATH$PATH/usr/local/bin

You can access individual elements with square brackets. Indexing starts at 1 from the beginning, and -1 from the end:

>echo$PATH/usr/bin /bin /usr/sbin /sbin /usr/local/bin>echo$PATH[1]/usr/bin>echo$PATH[-1]/usr/local/bin

You can also access ranges of elements, known as "slices:"

>echo$PATH[1..2]/usr/bin /bin>echo$PATH[-1..2]/usr/local/bin /sbin /usr/sbin /bin

You can iterate over a list (or a slice) with a for loop:

>forvalin$PATHecho"entry: $val"endentry: /usr/bin/entry: /binentry: /usr/sbinentry: /sbinentry: /usr/local/bin

Lists adjacent to other lists or strings are expanded as cartesian products unless quoted (see Variable expansion):

>set-la123>set-l1abc>echo$a$11a 2a 3a 1b 2b 3b 1c 2c 3c>echo$a" banana"1 banana 2 banana 3 banana>echo"$a banana"1 2 3 banana

This is similar to Brace expansion.

Command substitutions use the output of one command as an argument to another. Unlike other shells, does not use backticks ` for command substitutions. Instead, it uses parentheses:

>echoIn(pwd), running(uname)In /home/tutorial, running FreeBSD

A common idiom is to capture the output of a command in a variable:

>setos(uname)>echo$osLinux

Command substitutions are not expanded within quotes. Instead, you can temporarily close the quotes, add the command substitution, and reopen them, all in the same argument:

>touch"testing_"(date+%s)".txt">ls*.txttesting_1360099791.txt

Unlike other shells, does not have special syntax like && or || to combine commands. Instead it has commands , , and .

>cpfile1.txtfile1_bak.txt;andecho"Backup successful";orecho"Backup failed"Backup failed

Use , , and to conditionally execute code, based on the exit status of a command.

ifgrepfish/etc/shellsechoFoundfishelseifgrepbash/etc/shellsechoFoundbashelseechoGotnothingend

There is also a command:

switch(uname)caseLinuxechoHiTux!caseDarwinechoHiHexley!caseFreeBSDNetBSDDragonFlyechoHiBeastie!case'*'echoHi,stranger!end

Note that does not fall through, and can accept multiple arguments or (quoted) wildcards.

A function is a list of commands, which may optionally take arguments. Unlike other shells, arguments are not passed in "numbered variables" like , but instead in a single list . To create a function, use the builtin:

>functionsay_helloechoHello$argvend>say_helloHello>say_helloeverybody!Hello everybody!

Unlike other shells, does not have aliases or special prompt syntax. Functions take their place.

You can list the names of all functions with the keyword (note the plural!). starts out with a number of functions:

>functionsalias, cd, delete-or-exit, dirh, dirs, down-or-search, eval, export, fish_command_not_found_setup, fish_config, fish_default_key_bindings, fish_prompt, fish_right_prompt, fish_sigtrap_handler, fish_update_completions, funced, funcsave, grep, help, history, isatty, ls, man, math, nextd, nextd-or-forward-word, open, popd, prevd, prevd-or-backward-word, prompt_pwd, psub, pushd, seq, setenv, trap, type, umask, up-or-search, vared

You can see the source for any function by passing its name to :

>functionslsfunctionls--description'List contents of directory'commandls-G$argvend

While loops:

>whiletrueecho"Loop forever"endLoop foreverLoop foreverLoop forever...

For loops can be used to iterate over a list. For example, a list of files:

>forfilein*.txtcp$file$file.bakend

Iterating over a list of numbers can be done with :

>forxin(seq5)touchfile_$x.txtend

Unlike other shells, there is no prompt variable like PS1. To display your prompt, executes a function with the name , and its output is used as the prompt.

You can define your own prompt:

>functionfish_promptecho"New Prompt % "end New Prompt %

Multiple lines are OK. Colors can be set via , passing it named ANSI colors, or hex RGB values:

>functionfish_promptset_colorpurpledate"+%m/%d/%y"set_colorFF0echo(pwd)'>'set_colornormalend02/06/13/home/tutorial >

You can choose among some sample prompts by running . also supports RPROMPT through .

is an environment variable containing the directories in which searches for commands. Unlike other shells, $PATH is a list, not a colon-delimited string.

To prepend /usr/local/bin and /usr/sbin to , you can write:

>setPATH/usr/local/bin/usr/sbin$PATH

You can do so directly in , like you might do in other shells with . See this example.

A faster way is to modify the universal variable, which is automatically prepended to . For example, to permanently add to your , you could write:

>set-Ufish_user_paths/usr/local/bin$fish_user_paths

The advantage is that you don't have to go mucking around in files: just run this once at the command line, and it will affect the current session and all future instances too. (Note: you should NOT add this line to . If you do, the variable will get longer each time you run fish!)

starts by executing commands in . You can create it if it does not exist.

It is possible to directly create functions and variables in file, using the commands shown above. For example:

>cat~/.config/fish/config.fishset-xPATH$PATH/sbin/functionllls-lh$argvend

However, it is more common and efficient to use autoloading functions and universal variables.

When encounters a command, it attempts to autoload a function for that command, by looking for a file with the name of that command in .

For example, if you wanted to have a function , you would add a text file to :

>cat~/.config/fish/functions/ll.fishfunctionllls-lh$argvend

This is the preferred way to define your prompt as well:

>cat~/.config/fish/functions/fish_prompt.fishfunctionfish_promptecho(pwd)"> "end

See the documentation for funced and funcsave for ways to create these files automatically.

A universal variable is a variable whose value is shared across all instances of , now and in the future – even after a reboot. You can make a variable universal with :

>set-UEDITORvim

Now in another shell:

>echo$EDITORvim

If you want to learn more about fish, there is lots of detailed documentation, an official mailing list, the IRC channel #fish on , and the github page.

Sours: https://fishshell.com/docs/2.3/tutorial.html

Similar news:

The Fish Cookbook

This document is a living book of recipes to solve specific programming problems using the fish-shell.

Licensed CC BY-NC-SA 4.0

What's in the menu?

Setup

How do I install fish?

You can find directions in the official website or follow the instructions provided here for your OS.

How do I make fish my default shell?

Once you have installed fish and it's somewhere in your , e.g. /usr/local/bin, you can make it your default login shell.

echo /usr/local/bin/fish | sudo tee-a /etc/shells chsh -s /usr/local/bin/fish

How do I find out where fish is installed?

Use .

which fish /usr/local/bin/fish

Getting started

How do I learn fish?

The best way to learn fish is to dive in the official documentation and tutorial.

Where can I get help?

What's a prompt and what are all these ugly characters?

The prompt is where you type commands and interact with fish. Read more about the UNIX prompt here.

Maybe it looks like this:

[email protected] ~/C/fish-shell>

The tilde is a short way to show the home directory, rather than , , etc.

The is an arbitrary character I like to use to separate my username and my computer's name . You can learn to customize your prompt to show only what matters to you.

The forward slash is the path delimiter. At a glance, I can see the current directory is under the home directory, inside . I like abbreviated paths, so only is actually shown.

The greater-than symbol indicates the end of the prompt.

You don't like these conventions? Create your own prompt the way you want it.

See How do I create my own prompt in fish?

How do I find my current location in fish?

You can find out where you are via the read-only environment variable .

echo$PWD /Users/jb/Code/fish-shell

Another way to find out the current directory is via the builtin.

pwd /Users/jb/Code/fish-shell

In fish, both and always resolve symbolic links. This means that, if you are inside a directory that is a symbolic reference to another, you still get the path to the real directory.

Interactively, is easier to type. For scripting, is a function call less expensive.

How do I find and run commands in fish?

To run a command type the name of the command and press return.

Or, start typing the command you are looking for, and press tab. Fish will use the builtin pager which you can browse and select the command interactively.

Fish knows what commands are available by looking at the environment variable. This variable contains a list of paths, and every binary file inside any of those paths can be run by their name.

Print your contents.

printf"%s\n"$PATH /usr/local/bin /usr/bin /bin

or list every command in your system and display them in columns.

If the list is truncated, use:

Use and to navigate the list down / up, and to exit.

The variable is created at the start of the fish process during the environment initialization. You can modify, prepend or append to this variable yourself, e.g., in ~/.config/fish/config.fish.

Similar to the , and builtins previously introduced, *nix systems often include one or more shell-agnostic alternatives, e.g., , , , etc.

These commands overlap in functionality, but also possess unique features. Consult your system's manpage for details.

How do I check if a command succeeded in fish?

Every command returns an exit code to indicate whether they succeeded or not. An exit code of 0 means success. Anything else means failure. Different commands use different integers to represent what errors can happen.

You can check the exit code of any command using the read-only variable .

What is the fish shebang?

The shebang is a special comment that tells the shell to run a script with a particular program, e.g., , .

To run a script with by default, add a shebang to the first line in your file:

How can I interactively debug my fish scripts?

Use the builtin. Simply drop it anywhere in your script that you want to pause execution at and launch an interactive debugging prompt.

function helper set files (ls ~) breakpoint# when this is executed, an interactive prompt will be launched and you will be able to inspect $files# ... rest of function is not executed until you exit from debuggerend

Variables

How do I set variables in fish?

Use the builtin.

The builtin accepts the following flags to explicitly declare the scope of the variable:

  • , : available only to the innermost block
  • , : available outside blocks and by other functions
  • , : shared between all fish sessions and persisted across restarts of the shell
  • , : available to any child process spawned in the current session

If no scope modifier is used, the variable will be local to the current function; otherwise, it will be global.

If the variable has already been defined, the previous scope will be used.

How do I export a variable in fish?

Use the builtin and the scope modifier or .

set-x foo 42 fish -c'echo "foo=$foo"'# foo=42

How do I list all environment variables in fish?

Use the builtin without any modifier flags.

To print only the variable names, without the values, use .

To not truncate long lines use .

How do I set the persistently in fish?

The correct way to persistently add a path to your is using fish variable.

set-U fish_user_paths $fish_user_paths my_path

In fish 3.2.1 and later, you can use the builtin function instead.

See in the fish tutorial for more information.

How do I remove a path from the in fish?

Use the builtin with the or flag in combination with the builtin to find the index of the path you want to remove.

ifset-l index (contains-i$my_path$PATH) set-e PATH[$index] end

How do I remove a path persistently from the in fish?

Use the builtin with the or flag in combination with the builtin to find the index of the path you want to remove.

ifset-l index (contains-i$my_path$fish_user_paths) set-e-U fish_user_paths[$index] end

How do I check if a path exists in the in fish?

Use the builtin.

ifcontains$my_path$PATH# $my_path is in $PATHend

Functions

How do I create a function in fish?

Use the builtin.

function mkdirp mkdir-p$argvend

To make this function available in future fish sessions save it to ~/.config/fish/functions/mkdirp.fish. A clean way to accomplish this is using the function.

Alternatively, you can use the builtin to write the function definition to a file.

functions mkdirp > ~/.config/fish/functions/mkdirp.fish

How do I create a private function in fish?

You can't. In fish, functions are always public.

As a workaround, use a custom namespace to prefix any function you want to treat as private.

function _prefix_my_function end

It's not impossible to simulate private scope using .

Should function names and file names match?

Yes. The lazy-loading / autoloading mechanism relies on this convention to work.

If you have a file ~/.config/fish/functions/foo.fish with a valid function definition :

  1. In a new shell, trying to run produces an unknown-command error.
  2. Typing will highlight as a valid command, but produce an unknown-command error.
  3. Trying to run again now works as intended.

Can I define more than one function in a file?

Yes, you can. Note that fish does not have private functions, so every function in the file ends up in the global scope when the file is loaded. Functions are eagerly loaded as well, which it's not as effective as using one function per file.

How do I show the definition of a function in fish?

If you know the command is a function, use the builtin.

If you are not sure whether the command is a function, a builtin or a system command, use .

type fish fish is /usr/local/bin/fish

What's the difference between functions, builtins, and commands in fish?

System commands are executable scripts, binaries or symbolic links to binaries present in your variable. A command runs as a child process and has only access to environment variables which have been exported. Example: .

Functions are user-defined. Some functions are included with your fish distribution. Example: , , .

Builtins are commands compiled with the fish executable. Builtins have access to the environment, so they behave like functions. Builtins do not spawn a child process. Example: .

How do I list the functions defined in fish?

Use the builtin without arguments.

The list will omit functions whose name start with an underscore. Functions that start with an underscore are often called hidden. To show everything, use or .

Alternatively, launch the fish Web-based configuration and navigate to the /functions tab.

How do I check if a function exists in fish?

Use the function to query information about commands, builtins or functions.

ifnottype--quiet"$command_name"exit 1 end

Arguments

How do I access the arguments passed to a function in fish?

Use the variable.

function Foo printf"%s\n"$argvend Foo foo bar baz foo bar baz

How do I access the arguments passed to a script in fish?

Use the variable. Pass the arguments when running the script.

fish ./my_script foo bar baz foo bar baz

How do I parse command line arguments in fish?

Use a loop.

for option in$argvswitch"$option"case-f--foocase-b--barcase\*printf"error: Unknown option %s\n"$optionendend

For a more complete CLI parsing solution, see .

Aliases

How do I define an alias in fish?

Create a and save it to ~/.config/fish/functions.

function rimraf rm-rf$argvend

For backward compatibility with POSIX shells, use the function.

Avoid using inside ~/.config/fish/config.fish.

What's wrong with aliases?

Aliases created with will not be available in new shell sessions. If that's the behavior you need, then is acceptable for interactive use.

To persist aliases across shell sessions, create a and save it to ~/.config/fish/functions. This takes advantage of fish function lazy-loading / autoloading mechanism.

Using inside ~/.config/fish/config.fish will slow down your shell start as each alias/function will be eagerly loaded.

Configuration

Where's the .bash_profile or .bashrc equivalent in fish?

Your fish configuration is saved to ~/.config/fish/config.fish.

IO

How do I read from a file in fish?

To read a file line by line, use the builtin.

whileread-la line echo$lineend< my_file

How do I read from stdin in fish?

Use the builtin.

read--prompt"echo 'Name: ' "-l name

To read from an arbitrary input stream use together with the builtin.

whileread-la line echo$lineend

How do I redirect stdout or stderr to a file in fish?

Redirect stderr to .

my_command 2>$my_file

Redirect stdout to .

Redirect stdout to stderr.

Redirect stderr to stdout.

Concurrency

How do I run a command in the background in fish?

Use .

See also Background jobs in the fish documentation.

How do I check if background jobs are running in fish?

Use the builtin.

ifjobs> /dev/null echo Busy end

How do I synchronize two or more background tasks in fish?

Since fish there is a dedicated , but you can write your own if you are using an older fish.

First, to check if tasks are running in the background, parse the output from the builtin.

Then, block the foreground until all background jobs are finished.

functionwaitwhiletrueset-l has_jobs set-l all_jobs (get_jobs) orbreakfor j in$argvifcontains -- $j$all_jobsset-e has_jobs breakendendifset-q has_jobs breakendendend

How do I wait for a background process in fish?

Since fish there is a dedicated builtin to wait for a background process. For older fish distributions without , use the technique described in How do I synchronize two or more background tasks in fish?.

CC0

Sours: https://github.com/jorgebucaran/cookbook.fish


583 584 585 586 587