Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export function from zsh to bash for use in gnu parallel

How do I export a function from zsh, so that I can use it in gnu parallel?

example:

function my_func(){ echo $1;}
export -f my_func
parallel "my_func {}" :::  1 2

in bash will output

1
2

whereas in zsh it will output error messages

/bin/bash: my_func: command not found
/bin/bash: my_func: command not found
like image 653
Bilal Syed Hussain Avatar asked Mar 29 '14 23:03

Bilal Syed Hussain


4 Answers

This approach allows you to define a function in zsh (without worrying about adding a quote level). Also it does not require adding additional software.

Make a function. Here's one:

function bar {
    echo bar
    echo $1
}

And spin it up:

seq 10 | xargs -I{} -n1 -P1 zsh -c "$(whence -f bar); bar {}"

I'm using xargs at the minute but of course the same approach works for GNU Parallel, so thought I'd share it here.

like image 187
William Entriken Avatar answered Oct 21 '22 02:10

William Entriken


zsh does not have a concept of exporting functions. export -f somefunc will print the function definition, it will not export a function.

Instead, you can rely on the fact that bash functions are exported as regular variables starting with ():

export my_func='() { echo "$1"; }'
parallel --gnu "my_func {}" ::: 1 2 
like image 9
that other guy Avatar answered Nov 16 '22 19:11

that other guy


Based on that other guy's answer. You can write a function that export a zsh function that already defined to bash

function exportf (){
    export $(echo $1)="`whence -f $1 | sed -e "s/$1 //" `"
}

Usage

function my_func(){
    echo $1;
    echo "hello";
}

exportf my_func
parallel "my_func {}" :::  1 2
like image 6
Bilal Syed Hussain Avatar answered Nov 16 '22 17:11

Bilal Syed Hussain


A lot has changed since 2014.

Today you simply do:

# Activate env_parallel function (can be done in .zshenv)
. `which env_parallel.zsh`

function my_func(){ echo $1;}
env_parallel "my_func {}" :::  1 2

If your environment is big:

# Activate env_parallel function (can be done in .zshenv)
. `which env_parallel.zsh`

# Record which environment to ignore
env_parallel --session

function my_func(){ echo $1;}
env_parallel "my_func {}" :::  1 2
like image 5
Ole Tange Avatar answered Nov 16 '22 18:11

Ole Tange