You are not logged in.

#1 2022-10-29 19:42:12

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,595
Website

Bash script to run a function in a new xterm/tab

I have a complex function in a bash script that I would like to run in a new tab of my xterm (xfce4-terminal).  I can't seem to get the syntax right to run the function.  I can run a single command successfully.

Simplified script:

#!/bin/bash
doit () {
  echo "doing it"
  sleep 2s
}

export -f doit

targets=(foo bar)

for i in "${targets[@]}"; do
  xfce4-terminal --tab -T $i --geometry 128x36 -e 'sleep 5s'
done

That will create two new tabs each running the 'sleep 5s' command.
If I substitute 'sleep 5s' for my function, I get an error, "failed to execute child process "doit": Failed to execve: No such file or directory" so I am clearly not calling the functional correctly.

Any thoughts are welcomed.


CPU-optimized Linux-ck packages @ Repo-ck  • AUR packagesZsh and other configs

Offline

#2 2022-10-29 20:18:10

seth
Member
Registered: 2012-09-03
Posts: 49,951

Re: Bash script to run a function in a new xterm/tab

-e will run some executable - the internal bash function is meaningless in that context.
make it "$0 doit", and below the doit funtion as first action run

if [ "$1" = "doit" ]; then doit; exit 0; fi

Offline

#3 2022-10-29 20:23:28

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,595
Website

Re: Bash script to run a function in a new xterm/tab

The goal is to have the doit function run for all members of the targets array triggered by the for loop.  I am misunderstanding your suggestion.


CPU-optimized Linux-ck packages @ Repo-ck  • AUR packagesZsh and other configs

Offline

#4 2022-10-29 20:33:00

seth
Member
Registered: 2012-09-03
Posts: 49,951

Re: Bash script to run a function in a new xterm/tab

You cannot tell the TE to run some local bash function.
It wants to open an executable (/bin/sleep) from the disk and execute that.
A way around that is to execute the script itself and discriminate the behavior through parameters that you pass along, so w/ no parameter it will run your loop and if it gets a "doit" parameter it'll be doing it (in doubt processing more parameters)
The context of master instance will not be available to the slaves.

Edit:

#!/bin/bash
doit () {
  echo "doing it"
  sleep 2s
}

if [ "$1" = "doit" ]; then
  doit
  exit 0
fi

targets=(foo bar)

for i in "${targets[@]}"; do
  xfce4-terminal --tab -T $i --geometry 128x36 -e "$0 doit"
done

Last edited by seth (2022-10-29 20:34:52)

Offline

#5 2022-10-29 21:06:20

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,595
Website

Re: Bash script to run a function in a new xterm/tab

I understand now, thank you!


CPU-optimized Linux-ck packages @ Repo-ck  • AUR packagesZsh and other configs

Offline

Board footer

Powered by FluxBB