Skip to content
Biz & IT

Fish: the friendly interactive shell

Tired of those same old shells? Linux.Ars has an in-depth look at fish, a …

Ryan Paul – | 0
Story text

Introduction

Welcome back to Linux.Ars! We have some good stuff for you this week. Axel Liljencrantz has written a helpful introduction to the Friendly Interactive Shell (Fish), a unique and innovative command line environment with a number of useful improvements. Also included in this week’s Linux.Ars is an introduction to some of the new Javascript features of Firefox 1.5, and a brief introduction to Viewglob, a shell visualization utility.

Linux.Ars is all about you, so don’t be afraid to get involved! Want to do a section for a future edition? Have a suggestion for a topic that you want us to write about? I would love some feedback. We want your comments, complaints, suggestions, requests, free hardware, death threats, or disparaging remarks about my assorted deficiencies. Send me an e-mail or instant message, or post a comment in the discussion thread!

Developers Corner

New Javascript features in Firefox 1.5

Developers rejoice, Firefox 1.5 is finally here! The latest release of the Mozilla Foundation’s popular web browser includes numerous features that empower developers and improve the versatility of the platform. Support for SVG, the canvas tag, and the Javscript 1.6 standard make this release a cause of developer celebration.

Firefox 1.5 provides support for the latest enhancements to the Javascript language. E4X adds native XML support to Javascript and provides a complete object-oriented interface to XML content. With E4X, developers can manipulate XML content with unprecedented ease. XML tags can be assigned directly to a Javascript variable:

> var xmlcontent = <foo><baz>bar</baz></foo>;

And the tag contents can be extracted with a simple, object oriented syntax:

> xmlcontent.foo.baz
bar

E4X also provides support for tag interpolation. Developers can use braces to include values in constructed XML content:

> var xmlcontent = <foo><baz>{3 + 3}</baz></foo>;

With E4X, developers can iterate over tags based on simple queries, similar to the XPath syntax. In E4X, the .. operator is equivelent to the XPath // operator. To iterate over every B tag nested inside of the A tag, you can use the following syntax:

for each (var i in A..B) {
  // ...
}

You can further limit the loop and iterate over only the B tags that include a C tag that contains specific text:

for each (var i in A..B.(C == "value")) {
  // ...
}

Let’s look at a more elaborate example. Remember the monkey XML file from the last edition of Linux.Ars? Let’s revisit that example now with E4X:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Web Development Test Page</title>

    <script type="application/x-javascript; e4x=1">

      function main() {

  // create a variable and describe the XML content
  var animals =
<spaceapes>
  <monkey name="Gordo">
    <date>12/13/58</date>
    <species>Squirrel</species>

  </monkey>
  <monkey name="Able">
    <date>5/28/59</date>
    <species>Rhesus</species>
  </monkey>

  <monkey name="Baker">
    <date>5/28/59</date>
    <species>Squirrel</species>
  </monkey>
  <monkey name="Sam">

    <date>12/04/59</date>
    <species>Rhesus</species>
  </monkey>
</spaceapes>

  // create a variable to store the HTML content that will be added to the page
  //  note that we use the the + operator to concatenate a sequence of tags
  //  also note the use of the length() method, and { } for interpolation
  var monkey_content = <h1>Monkey Data</h1> +
   <p><b>Number of Monkeys:</b><i>{(animals..monkey).length()}</i></p> +
   <h2>Monkey List</h2>

  // create a new variable in which to construct our HTML monkey list 
  var monkey_list = <ul></ul>

  // iterate over each monkey in the XML document
  for each (var monkey in animals..monkey) {
    // append a list item with monkey details to our monkey_list variable
    monkey_list.innerHTML += <li><b>Name:</b><i>{monkey.@name}</i></li>

  }

  // append our new monkey list to the monkey_content variable
  monkey_content += monkey_list + <h2>Rhesus Monkeys</h2>

  // iterate over each Rhesus monkey in the XML document
  for each (var monkey in animals..monkey.(species=="Rhesus")) {
    // append the monkey name to the monkey_content variable
    monkey_content += <p><b>Name:</b>{monkey.@name}</p>
  }

  // append the value of the monkey_content variable to the inside of a div tag
  document.getElementById("monkeys").innerHTML += monkey_content
}
    </script>

  </head>
  <body onload="main()">
    
    <div id="monkeys" />

  </body>
</html>

Javascript 1.6 also adds support for new Array methods that facilitate functional sequence manipulation. With the map and filter methods, developers can now use anonymous functions to manipulate arrays without resorting to for loops. The following example will produce a new array that contains each value of the initial array multiplied by two:

> [1, 2, 3, 4, 5].map(function (x) { return x * 2 })
[2, 4, 6, 8, 10]

The filter method will pass each value of the array to the provided function, and return a new array that only includes the values that cause the function to return true :

> [1, 2, 3, 4, 5].filter(function (x) { return x > 3 })
[4, 5]

It is also possible to provide existing functions to the map and filter methods:

function isGreaterThanThree(x) {
  return x > 3
}

[1,2,3,4,5].filter(isGreaterThanThree)

You can learn more about new Javascript features at the Mozilla Developer Site.

Download the PDF
(This feature for Premier subscribers only.)

Tools, Tips, and Tweaks

Fish: the friendly interactive shell

Introduction

This is an in-depth look at fish, the friendly interactive shell. Fish is a GPLed commandline shell, written for Linux and other Posix-like systems. I felt there was a need for this article after all the attention that has been given to Monad, Microsoft’s upcoming shell. Unlike Monad, fish is not a new way to look at the shell concept. Fish is based on the same ideas as other Unix shells like bash and zsh, but contains many user interface improvements and makes shellscript into a proper programming language. Fish is a very cool shell full of exciting new ideas, fixes for a lot of old problems, and a well-thought-out design. You can trust me on this, since not only am I well known for my objectivity and love for the truth, I am also the main author of fish.

Design matters

Fish is not a pile of nice features. It has been carefully designed and then refined through a long process of trying out, modifying, and sometimes discarding features. The syntax has often changed in non-backwards-compatible ways many times in order to improve the language.

The fish syntax is designed to be as small and orthogonal as possible. Orthogonal, for those who aren’t algebra lovers, is more or less the property of beeing perpendicular. The fish language is designed so that instead of multiple similar features, there is an attempt to provide a single more powerful feature. This very consious design effort will show later on when describing the fish syntax for command substitution and functions.

Another important aspect of the fish design is that things that can be properly implemented outside of the shell, should not be implemented inside the shell.

  • Posix shells have (weak) arithmetic abilities, whereas fish instead relies on external programs like bc or expr. Bash offers some forms of regular expression matching; fish relies on external commands like expr, sed, grep and many others.
  • Most other shells contain a lookup table containing the full path to every command in order to avoid searching the whole path for a command. Fish instead relies on the operating system to perform caching for it. This reduces program complexity, and since only a single copy of the filesystem cache is needed, it saves memory. The performance implications of performing a PATH search are usually small compared to the cost of forking.
  • Most other Unix shells include built-in implementations of common commands like echo, kill, printf, pwd, time, and test. These internal implementations are usually slightly incompatible with the standard Unix tools they replace, making portability an even bigger hurdle. Making more and more commands a part of the shell also has stability implications, since a bug in the implementation of a command risks to crash the entire shell instead of only crashing a separate process.
  • There are many common commands that cannot be implemented as regular programs because they affect the shells internal state. Some of these, such as pushd, popd, umask and type are implemented as shellscript functions in fish.

Since the Posix syntax is well known, and has a huge user base, it makes sense to make a shell backwards compatible with it. But a large part of making the shell discoverable comes down to the shell syntax, and the Posix syntax has several missing or badly implemented features, including variable scoping, arrays, and functions. For this reason, fish strays from the Posix syntax in several important places. Fish remains Posix-compatible whenever there is no strong reason to stray from the Posix syntax. For a longer discussion on the fish design, see the fish design document.

User inteface matters

In his excellent Ars writeup on the Monad shell, Ryan Paul laments the lack of a nice user interface for Monad. Fish, on the other hand, has plenty of user interface polish.

  • X clipboard integration. If you are running X, ^K (kill), ^Y (yank) and related keyboard shortcuts in fish will use the X clipboard.
  • Syntax highlighting. Makes it a bit easier to parse a command, and much easier to detect errors, since syntax errors, invalid IO redirections, unknown switches to commands, and many other potential problems are flagged.
  • Tab complete anything. You can tab complete strings containing wildcards and bracket expantions
  • Command-specific tab completions. Fish ships with command specific completions for about 150 different commands. Complete using installed packages for the yum, rpm, and apt commands, complete using manual pages for the man command, complete using mountpoints for the mount and umount commands, complete using kernel modules for the modprobe command, complete using hostnames for the ssh command, the list goes ever on and on.
  • Descriptions for completions. All completions come with a description of what they mean. If you are looking for a manual page on a C string command type man str<TAB> and get a description of what each and every string function does. If you don’t know what switch enables the bandwith limiter for scp, type scp -<TAB> and see a list of all scp switches and a description of what they do scroll onto the screen.
  • Consistent help. Built-in commands in fish have -h and --help switches that display a short summary on how to use that command. These help messages are also shown on many types of syntax errors.
  • The open function. Fish ships with a command (not a built-in) called mimedb, which can use the Freedesktop.org mimetype database and .desktop files in order to identify the type of files and find the default application for a given filetype. This command is used by the open shellscript function to open a given file using its default application. For example, use open *.png to open all the PNG images in the current directory in the default PNG editor, usually the GIMP. The reason why open is a shellscript function and not a command itself is that there already exists a unix command with the name open. I could not come up with any other suitable name, so I made it a shellscript function. If a user of another shell wishes to use the same functionality, s/he can either use the mimedb command directly, or write an alias in his/her shell of choice.

There are many other improvements in the fish user interface, all aimed to make the shell more discoverable during interactive use, i.e., making it easy to discover how to use the fish shell. In fact, at least a quarter of all the code in fish is only used in interactive mode. There are thousands of tiny details that make your life ever so slightly easier in fish, things like highligting search matches when doing a history search, some clever coding to detect the difference between pressing the escape key and a terminal escape-code meaning that the escape key can actually be used, writing a message to the console when a background job exits at once if no other job is running, etc.

Fish ? syntax matters

Syntax matters

When fish 1.0 was released to the ‘Net almost a year ago, it contained most of the user interface features found today, but a rather-limited placeholder syntax. It quickly became painfully apparent that people where not willing to look past the fact that fish had a rather weak syntax and focus on whether the user interface had merit. For this reason, almost all my time spent on hacking fish in the last year has been spent on implementing a sane shellscript syntax. I have implemented most of the ideas I already had planned for fish, but many changes have been made along the way, both after suggestions and submissions from users and developers, and from new ideas that came along the way.

Block syntax

Shellscript is a programing language, and like most other programing languages, shellscript supports the notion of grouping multiple commands into blocks that have a special purpose. This purpose can be to perform a block of commands multiple times (a loop), to conditionally execute a block of commands (a conditional), or to simply refer to a large block of commands using a single short name (a function). Posix shellscript is not very consistent when it comes to block syntax. Blocks can either end with the opening keyword in reverse, such as fi or esac, using a special keyword such as done, or using a special operator such as ;; or }. Fish always uses the keyword end.

Posix syntax Fish syntax
if true; then echo hello; fi if true; echo hello; end
for i in a b c; do echo $i; done for i in a b c; echo $i; end
case $you in *) echo hi;; esac switch $you; case '*'; echo hi; end
hi () { echo hello; } function hi; echo hello; end

The second problem with the Posix block syntax is that most blocks may be executed in a different process than the main shell. This means that operations that change the shell state, such as variable assignments, are not guaranteed to actually have any effect in the shell proper. This is not the case with fish; in fish all commands without exception are evaluated by the same process. Bash is actually pretty good about not forking of subprocesses all the time, but if you ever want to write a portable shellscript, or if you want to combine loops and pipes, this will bite you.

Scoping

In Posix shell, all variables are global, i.e., they are shared between all running code. This makes it rather dangerous to name a loop variable $i, since if your code is called inside a loop using the same variable name, interesting things may happen. In fish, variables do have scope, and the default scope is the scope of the currently evaluated function, or global if no function is called.

set pirate Arrrr  begin  	set -l pirate Avast    	# Outputs 'Avast', since the local pirate variable shadows   	# the global variable  	echo $pirate   end    # Outputs 'Arrrr', since the local scoped pirate variable went  # out of scope  echo $pirate   	  

As can be seen in the above example, variable assignment is performed differently from other shells. In fish you use code like set foo bar to set the variable foo to the value bar. There are many reasons for this.

  1. To avoid the whitespace sensitivity, i.e. foo = bar and foo=bar meaning different things.
  2. To make variable assignment into just another command. In fish, everything, including loops, variable assignments and function definitions, are regular commands.
  3. To make scope and other nice features easily accessible using a single command. Use set -l foo bar to make foo a variable in the scope of the currently innermost evaluated block. Use set -g foo bar to make it a global variable.
  4. To make it easy to define and use arrays.

Speaking of arrays…

Arrays

Another missing feature of Posix shell is array variables. By contrast, all variables in fish are arrays. It just so happens that many arrays only have one element. To define the variable deer, with the values rudolph, blitzen, and humbert, use the command set deer rudolph blitzen humbert. See how easy that was? Here are a few more useful array commands:

Code Meaning
echo $deer[1 2] Write out the first and second elements of the array deer.
count $deer Output the number of elements in the variable deer.
set deer[2] dunder Set second element of the array deer to dunder
set -e deer Remove the variable named deer
set -e deer[1 2] Remove the first and second element of the variable deer. Only the third element, humbert, remains, and will thus be the new first and only element of the array.

On startup fish turns all environment variables into arrays using the : (colon) character as the separator element. This means that PATH, CLASSPATH, CDPATH and other common lists are arrays in fish, so you can do things like this:

for i in $PATH  	...  end

In fish, there are no positional parameters. Instead, arguments to the shell, as well as arguments to functions, are passed through the array variable $argv.

Functions

There are two Posix methods for creating a command that is evaluated inside the current shell, aliases and functions.

  • Aliases are defined using code like alias ll="ls -l". Aliases can be used anywhere in a pipeline, but they can not be given arguments and since they are only a single line long, they are very limited on what they can do.
  • Functions are defined using code like ll () { ls $*; }. Functions can not read from a pipe.

Aside from the problem with not beeing able to read from pipes, and the inconsistency of suddenly using {} to denote a block of code, functions have another syntax problem. Which of the following are a legal function definitions?

  1. hello () {echo hello }
  2. hello () {echo hello;}
  3. hello () {;echo hello }
  4. hello () {;echo hello;}
  5. hello () { echo hello }
  6. hello () { echo hello;}
  7. hello () { ;echo hello }
  8. hello () { ;echo hello;}

The not so obvious answer is that only number six is valid, all the others are syntax errors.

Fish functions are defined using code like function hello; echo hello; end, they can be used anywhere in a pipe, and they accept arguments. Arguments are inserted into the $argv array-variable.

Subshells, command substitutions, oh my!

Posix shells have three related concepts that deal with executing a piece of code in a process other than the main shell. These are subshells, command substitutions, and process substitutions. A subshell is a forked child shell that executes a command and then exits. A command substitution is a forked child shell that executes a command and then exits, and whose output is turned into arguments for another comman. Process substitution is a forked child shell that executes a command and then exits, and whose output is passed on to another command through a pipe. Got that? Unless you already knew what they where, probably not. The next section is an in-depth description of some Posix features. The more experienced readers can skip to the end, where the fish counterpart is described.

(ls)

Is the posix syntax for subshells. The above will cause a Posix shell to fork and the child will issue the ls command. We can see that the action takes place in another process by issuing a command that chnages the shell state, such as:

foo=bar  (foo=hello)  echo $foo

The second line assigns the value ‘hello’ to the variable ‘foo’, and the third line prints the value of the variable ‘foo’. But since the second line was executed by a different process, the output will be ‘bar’, not ‘hello’.

Next, let’s explain a command substitution. A command substitution works like a subshell, only the output of the command substitution is captured by the calling shell, and tokenized on newlines, and the result is passed as arguments to another commands.

convert $FILE $(basename $FILE .jpg).png

The above Posix command (it is not valid fish code) is a command substitution used to change the suffix of the filename stored in the $FILE variable from .jpg to .png. The output is then sent to the outer command, in this case the convert command, which is used to convert the JPEG to a PNG image.

Process substitution is very similar to command substitution. It is used to send the output of a command into the calling command, much like command substitution, but with the difference that the output is not sent through commandline arguments but through a named pipe, with the filename of the named pipe sent as an argument to the calling program.

The Posix syntax for process substitution looks like this:

diff <(sort foo.txt) <(sort bar.txt)

The above command will create two procces substitution processes, sorting the files foo.txt and bar.txt respectively. The output of these processes will go into a pair of pipes. The diff command will be started with a pair of filenames as arguments, with each of these filenames poiting to the reading end of the process substitution pipes.

The only concept described above that fish implements is command substitution. To group multiple commands into a single element one can use a block of commands, such as begin, ls, pwd, end, and as we shall see below, the fish syntax is powerful enough to implement a process substitution workalike as a simple shellscript function. Fish uses a slightly different syntax for command substitution than Posix shells. Where Posix shells can use either $() or `` to denote a subshell, fish uses simple parentheses, (). So the above command substitution example is written as follows in fish.

convert $FILE (basename $FILE .jpg).png

This is probably one of the least strongly motivated changes in fish syntax compared to Posix. The reason is simply that by doing so, $ is made to only denote variable expansion and nothing else, thus arguably making the syntax more consistent.

It should be noted that fish does not execute command substitutions in a second shell process, like Posix shells do. This means that even in command substitutions, it is legal to use built-in commands that change the shell state, such as variable assignments.

Verifiability

Since it is allowed to use variables as commands in regular shells, it is impossible to reliably check the syntax of a script. For example, this snippet of bash/zsh code may or may not be legal, depending on your luck. Do you feel lucky?

if true; then if [ $RANDOM -lt 1024 ]; then END=fi; else END=true; fi; $END

Both bash and zsh try to determine if the command in the current buffer is finished when the user presses the return key, but because of issues like this, they will sometimes fail. Even worse, this piece of perfectly legal code is rejected by bash:

FI=fi; foo() { if true; then true; $FI; }

Fish avoids this kind of problem, since variables are not allowed as commands. Anything you can do with variables as commands can be done in a much cleaner way using either the eval command or by using functions. Fish also avoids passing code into the shell as text as much as possible, to increase the amount of code that can be verified beforehand. Before starting to evaluate the contents of a file, fish runs extensive syntax checks on the code, meaning bugs and errors will be found as early as possible.

Quoting

The original Bourne shell was a macro language. It performed variable substitution, tokenization, and other operations on one line at a time without understanding the underlying syntax. This results in many unexpected side effects: Consider the following block of code:

smurf=blue;  smurf=evil; echo Smurfs are $smurf

On the Bourne shell, it will result in the output "Smurfs are blue." Macro languages like M4 and Bourne are not intuitive, but once you understand how they function, they are at least predictable and somewhat logical. Bash is implemented as a standard language using a bison grammar, but still chooses to emulate some of the quirks from the original Bourne shell. The above example would result in bash printing "Smurfs are evil."

On the other hand, variable values are still tokenized on spaces, meaning you can’t write rm $file, since if the variable file contains spaces, rm will try to remove the wrong files. To fix this, the user has to make sure every use of a variable is enclosed in quotes, like rm "$file". This is a very common source of bugs in shell scripts since it is simply a case of the default behavior being unexpected and very rarely what is wanted.

In summary, by making bash a non-macro language that sometimes behaves like one, it becomes unpredictable and very hard to learn. Fish is not a macro language and does not pretend to be one. Variables with spaces are still just one token.

Posix shells have four modes for writing text:

Style Example Description
Unquoted world=earth; echo hello $world prints "hello earth" Supports all types of parameter expantion except C-style backslash expantion, etc. The space and newline characters can be prefixed with a backslash to change their meaning.
Single quotes world=earth; echo 'hello $world' prints "hello $world" No parameter expantion is performed and the only special character that is recognized is the ‘ (single quote). Should not be confused with ` (backtick) which is used for command substitution.
Double quotes world=earth; echo "hello $world" prints "hello earth" Performs command substitution and variable expantion, the backslash and $ character are treated specially. Expanded variables are not tokenized on spaces or tabs.
Dollar quotes echo $'x68'ello $world prints "hello earth" Performs C-style backslash expantion.

Fish is not ideal when it comes to quoting either. There where initially only two modes for writing text, unquoted text, supporting all types of parameter expantion including C-style backslash expantion, and quoted text (using either single or double quotes) with no support for parameter expantion of any kind. Since a legion of users have complained about the lack of variable expantion when using double quoted strings, and since this can be used to expand an array variable into a single parameter token, I have caved in. The latest release of fish has three modes when writing text.

Style Example Description
Unquoted set world earth; echo hello $world prints "hello earth" Supports all types of parameter expantion, including C-style backslash expantion, etc.
Single quotes set world earth; echo 'hello $world' prints "hello $world" No parameter expantion is performed and the only special character that is recognized is the ‘ (single quote).
Double quotes set world earth; echo "hello $world" prints "hello earth" Only variable expantion is performed. Expanded variable arrays only result in a single argument.

I’m not entirely happy with having three separate modes for expanding text; this is a compromise to give users what they are used to, and to make some array operations easier.

Other features: Event handlers

When defining a new function in fish, it is possible to make it an event handler, i.e., a function that is automatically run when a specific event takes place, such as when a signal is delivered, when a specified job exits, or when a variable changes value. For example, specifying a signal handler for the WINCH signal is done by writing:

function --on-signal WINCH my_signal_handler  	echo Got WINCH signal!  end	  

Other features: Universal variables

Universal variables are environment variables whose value is shared across all users running instances of fish, and whose value is automatically preserved across reboots and logouts. All fish configuration variables (there aren’t many of them) are universal variables, meaning that when you change a fish setting, such as one of the syntax highlighting colors, the change takes effect at once on all your running fish instances. The syntax for defining a universal variable is very simple, just use the -U switch for the set built-in, like set -U foo bar.

A pretty cool example of universal variables in action can be had by opening up two fish terminals side by side and changing some color propery in one of the shells, for instance by issuing the command set fish_color_cwd blue. The current working directory part of the prompt in both running shells will turn blue at once.

Fish ? coding example

A fish coding example: Process substitution

This section will demonstrate how to implement a real-world script using the fish syntax. The script we will implement is a replacement for the Posix concept of Process substitution. I did not wish to add process substitution to fish, since I feel that it is far too similar to already existing fish concepts to warrant inclusion. The fish design document prohibits multiple related, but not identical features in favor of a single, more-powerful feature. But there are some cases where it might be desirable to have some form of process substitution workalike. Therefore, I started thinking about a way to implement a process substitution workalike. Such a workalike should ideally not require any special support from the shell, it should be a simple shell script function that relies on already generic language features. I’d like the syntax to be something like:

diff (sort foo.txt|psub) (sort bar.txt|psub)

That is, a regular command substitution and a pipe to a command called psub. The benefits with the above process substitution implementation are:

  • Instead of inventing new syntax elements, it integrates nicely with the rest of the language. In fish, pretty much everything is a regular command. The difference between a built-in and a regular command is made as small as possible.
  • It is much easier to discover this syntax, since the psub command will show up when tab-completing, and it is easy to get help on process substitution by issuing commands like psub -h, psub --help or help psub.

Naive psub implementation

The most obvious way to implement psub is to simply output the contents of the input pipe into a file, and write the filename to standard output. In fish syntax this would look something like this:

function psub     	# Find unique file name for writing output to  	while true  		set filename /tmp/.psub.(echo %self).(random);  		if not test -e $filename  			break;  		end  	end    	cat >$filename  	echo $filename  end	  

This solution has two large issues that we will fix in the upcoming sections:

  • This implementation is wildly inefficient. psub doesn’t finish until the whole pipeline is finished, meaning all process substitutions will be serialized. Also, all the data is temporarily stored on disk, which can make the transfer orders of magnitude slower.
  • The psub_temp file needs to removed when the command is finished

Better performance with named pipes

To improve psub, we need to stop writing to the filesystem and use a pipe instead. Luckily, Unix provides a command called mkfifo, which creates a pipeline that we can read and write to, and is connected to a regular file in the filesystem. Using mkfifo is trivial, simply use mkfifo FILENAME to create a pipe with the desired name. But there is a second problem, namely that the shell will wait for the command in the command substitution to finish before running the calling command. If we want all the commands to be able to run at once, the psub command must finish and return control to the shell. Fortunately, this turns out to be rather easy problem to solve; it is simply a matter of making the cat process, i.e., the process responsible for writing to the pipe, a background job. Background jobs, for those not familiar with them, are jobs that the shell starts without giving up control of the console, and without putting itself in the backround until the job exits. To make a job a background job, simply append the & symbol to the end of the job command. The new psub implementation now looks like this:

function psub    	# Find unique file name for writing output to  	while true  		set filename /tmp/.psub.(echo %self).(random);  		if not test -e $filename  			break;  		end  	end    	mkfifo $filename  	cat >$filename &  	echo $filename  end  

This is still not as efficient as bash process substitution, since it involves piping the output through the cat command. But the difference should be minimal in all but the most contrived cases.

Removing the temporary file

This problem is a bit trickier. After completing a command that uses process substitution, we need to clean up after ourselves, i.e., remove the named pipe that we created. Trouble is, we don’t want to do it before the calling command exits. Here the fish concept of event handlers comes to the rescue. What we are interested in here is to trigger an event when the calling job of the current command substitution exits. Since the caller has not yet been executed, it does not have a process ID to identify it with. Therefore, fish provides the special name caller to specify that the event should be triggered by the exit of the calling command. So a function definition like this one should be called once the calling command exits and then remove itself:

function foo --on-job-exit caller  	functions -e foo  end

A further problem is that to do its work, the event handler needs to know both the name of the file to delete and of itself. We can insert this information into the function body by constructing the function definition dynamically and passing it into the eval builtin.

This is what the psub command looks like once we have implemented a simple event handler to remove the pipe:

function psub    	# Find unique file name for writing output to  	while true  		set filename /tmp/.psub.(echo %self).(random);  		if not test -e $filename  			break;  		end  	end    	mkfifo $filename  	cat >$filename &    	echo $filename  		  	# Find unique function name  	while true  		set funcname __fish_psub_(random);  		if not functions $funcname >/dev/null ^/dev/null  			break;  		end  	end    	# Make sure we erase file when caller exits  	eval function $funcname --on-job-exit caller; rm $filename; functions -e $funcname; end    end

Aside from minor issues like documentation, variable declarations, etc., that’s the implementation of psub that is included with fish.

Caveat emptor

While a small, but talanted group of people have contributed greatly to the creation of fish, it is mostly the work of a single person with limited time. Because of this, and because of the short time that fish has been publically available, there are still bugs, missing features, performance issues and many other types of problems with fish. I, and many others use fish as their default shell for day-to-day work, and only very rarely do I encounter fish bugs. Users who run systems that are different from my own and that of the other fish developers are not always so lucky. Bug reports, fixes and questions are always welcome on the fish mailing list.

The future

There are still many ideas that I want to try out in fish:

  • Full terminal control. A future version of fish may include virtual terminal and a pass through for all data from commands evaluated by fish. This would enable features like an $ans variable containing the output of the last command to run, automatic paging of output, full mouse support including moving the cursor based on mouseclicks, choosing a completion from the completion pager by clicking on it, and many other features.
  • System integration. It would be nice if fish could use the default system colors (set through your desktop environment), use a graphical completion pager when running X, integrate the command history into the manu system of the terminal emulator, etc. Such changes obviously need to fail gracefully when using text-only connections.
  • Process specific universal variables, i.e. the option to set the value of a universal variable for only one specific instance of fish. Together with event handlers, this could be useful as a simple IPC mechanism.
  • Command-specific wildcards. It would sometimes be rather useful to let wildcards, i.e. * and ? match something other than filenames. For example, it could make sense to let them match package names for rpm and apt-get, etc.
  • Multiline editing. This is one of the few features i miss from bash and zsh.

Some of these ideas are mine, others where suggested on the fish mailing list. If you are interested in this type of discussion, join in.

Conclusion

I hope that after reading this you find fish exciting. (If not, why are you still reading?) Fish is free software, licensed under the GPL. It should work under any modern Posix-like system, it is known to work under Linux and with some minor issues, NetBSD, Solaris, and Mac OS X. It is already included in Debian unstable and in Arch Linux; I am doing a terrible job of maintaining a fish version in Fedora Extras (Could somebody please step up and do it for me?). It can be downloaded as a source tarball, source rpm, or i386 rpm from the fish homepage. Give it a try, it will make your life better*!

* May not actually make your life better.

Cool App of the Week

Viewglob

Viewglob is a powerful graphical utility that provides command line users with a visual display that indicates which files are targetted by a particular glob pattern. When run through a supported shell like Bash or Zsh, the Viewglob utility will launch a filesystem visualization window that lists the contents of the currently active directory, and automatically highlights files and directories targetted by a glob pattern as the pattern is typed. Viewglob will also show the contents of additional directories as the user types a path into the command line. Viewglob makes it easier to predict the consequences of commands, and it reduces the number of times that you have to use the ls command.

/dev/random

  • The Cairo-enhanced Clearlooks theme gets a sexy upgrade.
  • Gnome 2.13.2 has officially been released.
  • KDE design gurus launch the Oxygen site to show off their beautiful new icons.
  • A blogger has compiled a concise history of Linux.
  • A Linux blogger wrote a Klipper tutorial.
  • Rhythmbox gets some much-needed improvements.
  • Linksys releases a Linux-based router specifically for hobbyists.
  • Beagle 0.1.3 has been released and it includes Python bindings!
  • Beagle search integrated into Nautilus.
  • GStreamer 0.10 has been released. I may finally be able to stop using the xine backend for totem.
  • Galeon and Epiphany merge.
  • Siemens joins the Open Source Developer Labs.
  • Redhat pledges support for the creative commons.
  • Linus Torvalds thinks that Gnome users are idiots.
  • A Linux blogger makes a list of the ten most popular Ubuntu sites on the net.
Photo of Ryan Paul
Ryan Paul Ars Editor Emeritus
Ryan is an Ars editor emeritus in the field of open source, and and still contributes regularly. He manages developer relations at Montage Studio.
0 Comments

Comments are closed.