DEV Community

Discussion on: Writing Bash Scripts Like A Pro - Part 1 - Styling Guide

Collapse
 
baggiponte profile image
baggiponte

So which naming convention shall I use inside a loop? for _VAR in? Thank you for the guide!

Collapse
 
unfor19 profile image
Meir Gabay

The way I name it

declare -a _ITEMS=("first" "second" "third")
for item in "${_ITEMS[@]}"; do
    echo "Item name is ${item}"
done
Enter fullscreen mode Exit fullscreen mode

Output

Item name is first
Item name is second
Item name is third
Enter fullscreen mode Exit fullscreen mode

I usually name my iterator as item, even if it's a LIST_OF_ROWS or ARRAY_OF_THINGS I usually pick item as my iterator (in any lang).

So, as you can see, there's no clear preference, just go with what suits you, and if you find item to be good for you, go for it

Collapse
 
baggiponte profile image
baggiponte

Thank you for the reply! Guess a guide on arrays would also be super useful - the example you made right here was more clarifying than many web articles I have read...

Thread Thread
 
unfor19 profile image
Meir Gabay

I'll definitely cover arrays in my next blog post, thank you for the feedback, much appreciated!

Thread Thread
 
baggiponte profile image
baggiponte

Also, off the top of my mind: getopt for flags and parallel to avoid writing loops in scripts (I’m just being creative)

Thread Thread
 
unfor19 profile image
Meir Gabay • Edited

Would you believe me if I told you that I've never, ever, used getopts or paralllel ? 🙈 I Never had the need to ... I found better alternatives that were easier to "memorize".

getopts - See bargs; A framework for creating a Bash CLI. You would expect me to use getops for the "Usage" menu ... But I haven't, I used other tricks to make it work

parallel - I've never processed big files in Bash, if I need to go down this road, I'll probably use Go, where it's more inclined towards parallelism and threading. I do use background jobs, but mainly for short processes which don't require "blocks of data". Instead, I use background jobs, which is simply adding & to a command and wait in the bottom of the file to wait for it to finish. For example "downloading 5 files in parallel" or "encrypting 10 files in parallel".

curl -o file1 https://example.com/file1 &
curl -o file2 https://example.com/file2 &
curl -o file3 https://example.com/file3 &
curl -o file4 https://example.com/file4 &
curl -o file5 https://example.com/file5 &

wait # for all jobs to finish ...
Enter fullscreen mode Exit fullscreen mode

It's also a matter of time/knowledge; if you know getopts and parallel then use them. If you don't, feel free to pass it, as I haven't found it "mandatory", but that's me.

Thread Thread
 
baggiponte profile image
baggiponte

I didn’t know about bargs! That’s precious advice, thank you!