ivkremer
ivkremer

Reputation: 1275

How to use bash functions with fish

I have few bash functions like

#!/bin/sh

git-ci() {
    ...
}

When I was not using fish I had a source ~/.my_functions line in my ~/.bash_profile but now it doesn't work.

Can I use my bash functions with fish? Or the only way is to translate them into fish ones and then save them via funcsave xxx?

Upvotes: 4

Views: 5663

Answers (4)

Adham Zahran
Adham Zahran

Reputation: 2180

As @Barmar said fish doesn't care about compatibility because one of its goals is

Sane Scripting

fish is fully scriptable, and its syntax is simple, clean, and consistent. You'll never write esac again.

The fish folks think bash is insane and I personally agree.

One thing you can do is to have your bash functions in separate files and call them as functions from within fish.

Example:

Before

#!/bin/bash

git-ci() {
    ...
}

some_other_function() {
    ...
}

After

#!/bin/bash
# file: git-ci

# Content of git-ci function here
#!/bin/bash
# file: some_other_function

# Content of some_other_function function here

Then put your script files somewhere in your path. Now you can call them from fish.

Upvotes: 5

mmmmmm
mmmmmm

Reputation: 32661

There is a program babelfish that will translate bash scripts to fish.

For example your script

git-ci() {
echo "Hello"
}

is translated to

function git-ci
  echo 'Hello'
end

Upvotes: 2

Oceanlight
Oceanlight

Reputation: 33

If you don't want to change all the syntax, one workaround is to simply create a fish function that runs a bash script and passes the arguments right along.


Example

If you have a function like this

sayhi () { 
    echo Hello, $1!
}

you'd just change it by stripping away the function part, and save it as an executable script

echo Hello, $1!

and then create a fish function which calls that script (with the name sayhi.fish, for example)

function sayhi 
    # run bash script and pass on all arguments
    /bin/bash absolute/path/to/bash/script $argv
end

and, voila, just run it as you usually would

> sayhi ivkremer
Hello, ivkremer!

Upvotes: 3

Barmar
Barmar

Reputation: 780889

The syntax for defining functions in fish is very different from POSIX shell and bash.

The POSIX function:

hi () { 
    echo hello
}

is translated to:

function hi
    echo hello
end

There are other differences in scripting syntax. See the section titled Blocks in Fish - The friendly interactive shell for examples.

So it's basically not possible to try to use functions that were written for bash in fish, they're as different as bash and csh. You'll have to go through all your functions and convert them to fish syntax.

Upvotes: 4

Related Questions