The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

If you can read me, I'm broken!

Views: 1,907β€…    Votes:  5β€…
Tags: bash   scripts  
Link: πŸ” See Original Answer on Ask Ubuntu ⧉ πŸ”—

URL: https://askubuntu.com/q/1181605
Title: Is a for loop using arrays better than using field splitting on a simple variable?
ID: /2019/10/17/Is-a-for-loop-using-arrays-better-than-using-field-splitting-on-a-simple-variable_
Created: October 17, 2019    Edited:  June 12, 2020
Upload: September 15, 2024    Layout:  post
TOC: false    Navigation:  false    Copy to clipboard:  false


Answer to original title

The original title asked β€œwhat type of for loop is better”.

For myself, the best method is the fastest one. To find out prepend the time command to your script or function. Some examples:

$ time du -s

real    0m0.002s
user    0m0.003s
sys     0m0.000s

$ time ls

real    0m0.004s
user    0m0.000s
sys     0m0.004s

It is important to flush cached buffers in-between tests though:

If two loops are about the same in speed, I’ll pick the one with best readability.

The scope of this question is makes speed irrelevant though because most of the time is spent waiting for user input and there are only a maximum of 10 windows open for most people.


Answer to body of question

Other answers focus on rewriting the script so I’ll give my two cents worth too.

The line:

list=$(wmctrl -l | awk ' !/-1/ { print $1 } ')

So I would use:

Windows=( $(wmctrl -l | awk ' !/-1/ { print $1 } ') )

The line:

wmctrl -i -a $i

There are two ways of writing a shorter more readable script, first with an array:

#!/bin/bash
Windows=( $(wmctrl -l | awk ' !/-1/ { print $1 } ' ) )
for Window in "${Windows[@]}" ; do wmctrl -ia $Window -c $Window ; done

second without an array:

#!/bin/bash
Windows=$(wmctrl -l | awk ' !/-1/ { print $1 } ' )
for Window in $Windows ; do wmctrl -ia $Window -c $Window ; done

I prefer the array method because I’m trying to learn more about them and want to use them as much as possible. The choice is yours however.

⇧ Zenity progress: no window Intel wifi Support for AX200 (Cyclone Peak)  β‡©