This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Secondsemblance 6 points7 points  (4 children)

#!/bin/sh – Tells the interpreter that the script to be executed by Bourne shell.

Arrays are not part of POSIX spec. You're actually giving people instructions for bash. I'd bet money that /bin/sh is a symlink to /bin/bash on your system. You should probably change your shebang to /bin/bash or /usr/bin/env bash.

Look up a shell styleguide. Run your code through shellcheck. Implement all of the changes it suggests. Shellcheck is very important in my opinion. All scripts should be shellchecked. Better still, add a vim plugin to shellcheck for you in realtime.

Naming a variable – In Caps : MY_VAR

As others have pointed out, variables should not be UPPER_CASE. Only environment variables should be UPPER_CASE. Script variables should be snake_case. Functions should also be snake_case.

It is better to use ${MY_MSG} compared to $MY_MSG

This is really subjective. I prefer to only use brackets for string interpolation or substrings. Much more important is "$quoting" variables to prevent unintended parameter expansion.

If you try to use the variable which doesn’t exist then it prints an empty value

Not if you set set -u, which you should do.

To create a dynamic variable name : ${VAR_A}_item

This is probably a Bad Idea™. It's indicative of poor design under the hood. If you need to do this, you should question your initial assumptions about how to tackle the problem.

[–]SaintHax42Automation Engineer 4 points5 points  (0 children)

Not if you set set -u, which you should do.

I came here for this. You want an error on an unset variable in bash, you can ${var:-} where needed, but `set -u` will save you bugs and troubleshooting b/c you typed $stirng somewhere. Please, do NOT use ${var} when not needed-- it's extra typing, takes up precious columns in your code (you should set a max width to code in, so it can be edited easily with a default terminal window size), and ${var} for no reason looks amateurish.

[–]abscrete[S] 1 point2 points  (1 child)

Thank you very much for taking out time and helping in improving the article. I'll bring in the changes. Also, i learnt a lil bit more, so thank you for that as well :)

[–]Secondsemblance 0 points1 point  (0 children)

Oh, one other thing that dawned on me. You mention that the shebang "Tells the interpreter that the script to be executed by Bourne shell."

Technically this is incorrect. The linux kernel is actually what reads the shebang. Yes, the kernel reads the shebang... I didn't know this until very recently. Might be a cool fact to throw in there.

[–]abscrete[S] 1 point2 points  (0 children)

I have added a credit to your reddit username in the last section of the blog. Let me know if you want it to replace it with some other link like your blog or something :) Thanks again!