pogibas
pogibas

Reputation: 28339

bash export command that has a variable in it

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

Answers (2)

Carl Norum
Carl Norum

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:

  1. removed unnecessary export
  2. put {} around variable names
  3. double-quoted ${FILE} in case there are files with spaces in their names
  4. got rid of the $() and replaced it with ''
  5. fixed up indentation for easier reading
  6. changed for loop list to * from ./* for less typing

Upvotes: 1

Charles Duffy
Charles Duffy

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

Related Questions