Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inline an array of strings in a bash for loop?

Tags:

How do I inline an array of strings in a bash for loop ? This works:

array=(one two) for i in ${array[*]};do echo $i; done 

But I'd like to eliminate the extra local variable. I've tried many variations that seem reasonable, for example:

for i in ${("one" "two")[*]};do echo $i; done 

or

for i in ${"one" "two"};do echo $i; done 

In each case, it treats one and two as commands :(

like image 992
expert Avatar asked Dec 11 '15 21:12

expert


People also ask

How do I loop through an array in bash?

There are two ways to iterate over items of array using For loop. The first way is to use the syntax of For loop where the For loop iterates for each element in the array. The second way is to use the For loop that iterates from index=0 to index=array length and access the array element using index in each iteration.

How do I loop through a string in bash?

Create a bash file named 'for_list1.sh' and add the following script. A string value with spaces is used within for loop. By default, string value is separated by space. For loop will split the string into words and print each word by adding a newline.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

Did you try with:

for i in "one" "two"; do echo "$i"; done

like image 134
Alija Bevrnja Avatar answered Nov 01 '22 21:11

Alija Bevrnja