DEV Community

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

Collapse
 
unfor19 profile image
Meir Gabay

@zoulja Good point!

I prefer using named variables instead of positional arguments. So the logic of my code is based on names instead of indexes, such as $1, $2 and so on. This way, even if the order of given arguments is changed, I still maintain my function's logic.

And of course, let's learn by example; assuming we create the greet() function

greet(){
  local name="$1"
  local age="$2"

  echo "Hello ${name}, you're ${age} years old."
}

# Usage
greet "Willy" "33"
Enter fullscreen mode Exit fullscreen mode

Now, I want to change the positional arguments, so the function consumes age and then name

greet(){
  # I switched between $1 and $2
  # Also changed the order of variables so it makes sense
  local age="$1"
  local name="$2"

  # Didn't touch the logic
  echo "Hello ${name}, you're ${age} years old."
}

# Usage
greet "33" "Willy"
Enter fullscreen mode Exit fullscreen mode

I hope that explains it