LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   [scripting] try to passing arguments to for cycle (inside a function) (http://www.linuxquestions.org/questions/linux-general-1/%5Bscripting%5D-try-to-passing-arguments-to-for-cycle-inside-a-function-877266/)

vomplete 04-26-2011 06:22 PM

[scripting] try to passing arguments to for cycle (inside a function)
 
Hi

The code:

Quote:

#!/bin/bash
# Dummy list
ls -1 / >> list.txt

# Function definition
ReadFileLines() {
for i in $(cat $1)
do
$2
done
}

# Run
ReadFileLines "list.txt" "echo $i"

Problem: I need a method to maintain the $i variable.
In fact, actually, this variable get lost when executed.
I think that an escape can preserve this variable and permit its execution inside the function, but I've no idea about.

Any ideas?

corp769 04-26-2011 06:29 PM

Are you trying to run the [ReadFileLines "list.txt" "echo $i" ] only once, or do you want it ran every time the for loop sequences? From what I can see though, you can declare another variable and set it to the value of i, just make sure to declare it outside of the for-loop scope.

Kind regards,

Josh

crts 04-26-2011 06:35 PM

Hi,

try this
Code:

#!/bin/bash
# Dummy list
ls -1 / > list.txt
# Function definition
ReadFileLines() {
for i in $(cat $1)
do
eval $2
done
}
# Run
ReadFileLines "list.txt" 'echo $i'

While the above example "works" I still wonder why you would want to do this in such a peculiar way. Why don't you simply do
echo $i

inside the for-loop instead of expanding a variable that holds an instruction?

vomplete 04-26-2011 07:01 PM

Quote:

Originally Posted by crts (Post 4337354)
Hi,

try this
Code:

#!/bin/bash
# Dummy list
ls -1 / > list.txt
# Function definition
ReadFileLines() {
for i in $(cat $1)
do
eval $2
done
}
# Run
ReadFileLines "list.txt" 'echo $i'

While the above example "works" I still wonder why you would want to do this in such a peculiar way. Why don't you simply do
echo $i

inside the for-loop instead of expanding a variable that holds an instruction?




thanks 10000!!! :cool:

solved!


All times are GMT -5. The time now is 07:39 PM.