4 ms·
Even more correct would be to use an array: stuff=("foo foo" "bar" "baz") for route in "${stuff[@]}"; do curl localhost:8080/"$route" done
by lambic 5y ago
Even more correct would be to use an array:
stuff=("foo foo" "bar" "baz")
for route in "${stuff[@]}"; do
curl localhost:8080/"$route"
done
- gcmeplz 5y ago"${stuff[@]}" would be turning it back into "foo bar baz" though, right? I think if you were using arrays for this, it'd be something like: stuff=("foo" "bar" "baz"); array_length=${#stuff[@]}; for i in $(seq 0 $array_length); do curl localhost:8080/${stuff[i]} done I'm betting even that isn't right: as soon as bash arrays are a thing, I reach for a different language. [edit]: trying to get formatting correct
- computronus 5y ago"${stuff[@]}" expands into the elements of the array, with each one quoted - so even that first "foo foo" element with a space will be handled correctly. That is how I would write the loop as well, in general. However, your technique also works, with some tweaks: * The loop goes one index too far, and can be fixed with seq 0 $(( array_length - 1 )) * There should be quotes around ${stuff[i]} in case it has spaces
- gcmeplz 5y agoOh, that's way better for sure! Thanks for the explanation
- deleted 5y ago[deleted]
- cjvirtucio 5y agoand on the off-chance that `stuff` must be a space-separated string for w/e reason: IFS=' ' read -ra routes <<<"${stuff}" for route in "${routes[@]}"; do curl localhost:8080/"$route" done
- chubot 5y agoYes that is more correct, I describe that here: Thirteen Incorrect Ways and Two Awkward Ways to Use Arrays http://www.oilshell.org/blog/2016/11/06.html http://www.oilshell.org/blog/2016/11/06.html In Oil the syntax is simplified to const stuff = %("foo foo" bar baz) for route in @stuff { curl localhost:8080/$route # no quotes needed }
- xorcist 5y agoThe bash syntax for arrays is obtuse and no one will spot when an error creeps in. It's worth to make an effort to say with space separated strings, as long as you are with bash. More advanced data structures is often an indication that it's worth glacing at something like python. Should you need to handle spaces, it is often much easier to go with newline separated strings and use "| while read". This contruction has the added benefit of the data not needing to fit in your environment. This can be a real issue, and is not at all obvious when it happens.