LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How can i use variables as the initial and final values of a variable in for loops (https://www.linuxquestions.org/questions/linux-newbie-8/how-can-i-use-variables-as-the-initial-and-final-values-of-a-variable-in-for-loops-912851/)

cijin 11-10-2011 10:13 AM

How can i use variables as the initial and final values of a variable in for loops
 
How can i use variables as the initial and final values of a variable in for loops

suicidaleggroll 11-10-2011 10:15 AM

In what language?

sinuhe 11-10-2011 10:38 AM

posix shell for and variables
 
The first argument to for is defined as part of the for statement, but the word list could use a preset variable, which you could unset after the for loop.

Was that what you were asking, or did I misunderstand?

David the H. 11-10-2011 07:44 PM

How about showing us an example of what you're thinking? At least show us the inputs and the desired output.

The for loop syntax is quite simple:
Code:

for variable in word word word; do
        commands
done

The list of words is read after parameter expansion, so if you have variables containing words, or any other kind of substitution, then their contents will simply become part of the list.

Code:

var1='a b c'
var2='d e f'
echo 'foo bar baz' > file.txt

for var in $var1 "$var2" $( cat file.txt ) ; do
        echo "[$var]"
done

Notice how quoting affects the result. The contents of a quoted variable will be seen as a single element, while an unquoted one will be word-split before the loop read it.


All times are GMT -5. The time now is 11:52 AM.