0

I need to execute two commands in the background

function "$arg1" "$agr2" arg3 && declare "workspaces=$arg3"

first it will execute function if it complete then it will initialize arg3 in workspace(it is global var) and whole process should run in background

I tried

function "$arg1" "$agr2" arg3 && declare "workspaces=$arg3" & //this didn't work
(function "$arg1" "$agr2" arg3 && declare "workspaces=$arg3") & //niether this

I don't want to execute both in parallel because in this case workspace will not initialize

  • Can you provide more information about what this function is doing and what are arg[1-3] ? – mrc02_kr Oct 15 '18 at 9:15
  • @mrc02_kr function calling another script that is taking more time and args are simply string variables like arg1="file1 file2 file3" and arg2="file1" and arg3="" – Sudhir Tiwari Oct 15 '18 at 10:37
  • Try, function "$arg1" "$agr2" arg3 & declare "workspaces=$arg3" & – msp9011 Oct 15 '18 at 11:05
  • or (function "$arg1" "$agr2" arg3 &) && (declare "workspaces=$arg3" &) – msp9011 Oct 15 '18 at 11:06
  • It didn't work arg3 values is null in this case for (declare "workspaces=$arg3" &) – Sudhir Tiwari Oct 15 '18 at 11:53
0

I believe the problem you're running into is that you're expecting the global variable $workspaces to be set as a result of this function. However, you can't set a global variable (in shell terms, an export) on the current shell from a subshell. And the only way you can run a command in background is by running it in a subshell. Therefore, running declare or export as part of a background command will not set that variable in the current shell, which seems to be what you're trying to achieve.

0

It is really unclear to me what you are trying to do.

My guess is that you can use parset from GNU Parallel as part of the solution:

# Activate parset
. `which env_parallel.bash`

export -f myfunction
parset myresult -j0 myfunction {} ::: arg1 arg2 arg3
echo "${myresult[0]}"
echo "${myresult[1]}"
echo "${myresult[2]}"

This will run these commands in parallel:

myfunction arg1
myfunction arg2
myfunction arg3

and put the output from each of them in the array myresult.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.