Reputation: 28339
I have command that script uses in many loops and want to export it.
#!/bin/bash
export COMMAND=$(many programs $FILE)
# And use this command latter like this:
for FILE in ./*;
do
eval $"COMMAND"
done
And I can't export this command as I get an error from the programs in this COMMAND (please provide the input).
How can I export COMMAND with a variable in it?
Edit
I have used @Charles Duffy answer but have an additional problem:
your_command() {
do_something_with "$1"
do_something_else_with "$1"
}
export -f your_command
for i in $(seq 1 $Times); do
for file in ./*; do
your_command "$file"
done
done
When Times
=1 loop works fine, but when Times
=2 your_command
does not save the output (there is an output for the first loop, but not for the second).
Upvotes: 1
Views: 108
Reputation: 224944
First off - you should use a function, as described in other answers. That said, it's possible to fix what you have, too. You probably shouldn't be using $()
. The way you have it, your "many programs" will run immediately when initializing COMMAND
, and you'll save their output, not the command line itself. Besides that, $FILE
isn't set yet at that point. Here's a modified version of your script that should work:
#!/bin/bash
COMMAND='many programs "${FILE}"'
# And use this command later like this:
for FILE in *
do
eval ${COMMAND}
done
Changes I made to your script:
export
{}
around variable names${FILE}
in case there are files with spaces in their names$()
and replaced it with ''
for
loop list to *
from ./*
for less typingUpvotes: 1
Reputation: 295463
Your command
should be a function, not a variable.
your_command() {
do_something_with "$1"
do_something_else_with "$1"
}
for file in ./*; do
your_command "$file"
done
If you really need this to be exported (available to subprocesses), you can do that with the following:
export -f your_command
Upvotes: 4