Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fish shell -eq and -a in if statement

I was reading the git.fish completion script (/usr/local/Cellar/fish/2.1.2/share/fish/completions) for fish shell and I ran into some problems with understanding what the syntax means.

In the block,

function __fish_git_needs_command
  set cmd (commandline -opc)
  if [ (count $cmd) -eq 1 -a $cmd[1] = 'git' ]
    return 0
  end
  return 1
end

I understand that cmd is set as commandline -opc. But in the next statement (count $cmd) -eq 1 -a $cmd[1] = 'git', what do -eq and -a mean?

I am new to fish shell and I am trying to understand the syntax by trying to write my own completion script for a program. Help would be greatly appreciated.

Thank you.

like image 517
Hasit Mistry Avatar asked May 26 '15 00:05

Hasit Mistry


2 Answers

In fact -eq and -a are not part of fish syntax. They are ordinary arguments!

if [ (count $cmd) -eq 1 -a $cmd[1] = 'git' ]

The opening square bracket here is actually a command, like cat or grep. You really do have a file /bin/[. It may be easier to understand via the test command, which is the same thing:

if test (count $cmd) -eq 1 -a $cmd[1] = 'git'

Now it's easy to see that -eq and -a are just ordinary arguments being passed to test, with no syntactic significance to fish.

test has its own little language like awk or sed. See man test to learn about it.

like image 162
ridiculous_fish Avatar answered Sep 20 '22 10:09

ridiculous_fish


The -eq is an integer comparison function.

The -a is a logical and.

So the logical equivalent would be something like:

if [ (count $cmd) == 1 && $cmd[1] == 'git' ]

(in Java pseudo-syntax).

Background

The reason why -eq is used is because a shell normally works with text processing only. As a result numbers are stored in "strings". Sometimes two numbers are equivalent, but not string-equivalent. For instance the following example:

if [ "01" -eq "1" ]
then
    echo "integer equal"
fi
if [ "01" = "1" ]
then
    echo "string equal"
fi

Will only print integer equal.

like image 26
Willem Van Onsem Avatar answered Sep 18 '22 10:09

Willem Van Onsem