LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Running commands from array in a child bash script (https://www.linuxquestions.org/questions/programming-9/running-commands-from-array-in-a-child-bash-script-594816/)

bengoavs 10-26-2007 11:20 AM

Running commands from array in a child bash script
 
Hi guys, kind of a newbie question, so I apologize in advance.
First I tried to export an array from one script to it's child, and I figured it's not supported in bash (would be happy if someone can correct me). So I pass the array cells one by one. It works for all commands except for those with redirection signs (| > etc.), see example and error below. Your help is appreciated!!

main.sh:
CMDS=("ls -l > /tmp/log")
~/child.sh "${CMDS[0]}"

child.sh:
for i in "$@"
do
if [ "$i" ]; then
echo "$i"
$i
fi
done


./main.sh
ls -l > /tmp/log
ls: >: No such file or directory
ls: /tmp/log: No such file or directory

matthewg42 10-26-2007 12:33 PM

child.sh takes each of the strings passed on the command line and tries to execute them as a program. However, it does not split them with IFS. You want to "eval $i", like this
Code:

#!/bin/bash
# this is child.sh

for i in "$@"
do
        if [ "$i" != "" ]; then
                echo "$i"
                eval $i
        fi
done

By the way, you can put ode fragments in [code] tags - this will preserve formatting and use a fixed width font to aid readability.

Regarding he exporting of arrays: environment variables are passed between processes as an array of strings only.

bengoavs 10-26-2007 02:16 PM

Thanks a
Code:

LOT
Man !


All times are GMT -5. The time now is 03:18 PM.