icy/bash-coding-style

On naming variables

cmpitg opened this issue · 3 comments

With regards to the variable names section, is there any rationale other than to prevent naming clash to prefix variables with an underscore? How about suffixing rather than prefixing? E.g. instead of

_my_def() {
  local _d_tmp="/tmp/"
  local _f_a=
  local _f_b=

  # This is good, but it's quite a mess
  local _f_x= _f_y=
}

how about

my_def_() {
  local d_tmp_="/tmp/"
  local f_a_=
  local f_b_=

  # This is good, but it's quite a mess
  local f_x_= f_y_=
}

I personally think suffixing makes it much less cluttered and more readable. What do you think?

icy commented

Thanks @cmpitg for your comments.

The problem with #bash is that a variable can't stand with its own name. You have to use a $ to get variable value. Let's see

local _my_var=something

echo "My value is $_my_var, or ${_my_var}. Uppercase version is ${_my_var^^}".
echo "My value is $my_var, or ${my_var}. Uppercase version is ${my_var^^}".

The primary purpose of the underscore (_) is to create a natural distance between the dollar ($) and the variable name. I see that helps my code more readable, esp. when I have no color in my viewer.

This is just a convention, and you may follow it , or not. The most important thing to remember is to make sure your code consistent, by not using different styles in the same project;)

Thanks @icy.

The primary purpose of the underscore (_) is to create a natural distance between the dollar ($) and the variable name. I see that helps my code more readable, esp. when I have no color in my viewer.

This explains it. Would it be better if a brief rationale is added for some section? Some could be subjective, but I think it'd be better to understand the decision at least. Don't you think?

icy commented

Totally agreed. I will update it soon :)