What are the best programming habits

Advice: Using shells for Linux and Unix correctly

Program loops

You can also program loops in shell scripts. This is what the for-do-Command:

There are a few file names in the variable here FILELIST. The command for recognizes the list based on the spaces it contains and goes through them one after the other. Each list entry becomes the variable FILENAME assigned. Then the file that is currently in turn is copied. Note that after a for a do must stand and that at the end of the loop done belongs.

Command line parameters in the script

The script is not yet very independent. It would be better if you could pass the above list as a command line parameter, i.e. in the form:

and so on. It works like this:

This means that the program also understands command line parameters. First, however, it checks whether the parameters are available. This works best with the special variable $#. This contains the number of parameters passed. With if [$ # -lt 1]; then the script checks whether there are fewer than one parameter. If this is the case, the script outputs an error message and brief instructions on how to use it. Here comes $0 for use. This variable contains the program name itself.

If there are enough parameters, a WhileLoop in place. It counts the number of available parameters with each run while [$ # -gt 0]. The -gt stands for "greater than". As long as this condition applies, the following loop will always use the parameter $1 of the variables FILENAME assigned. The command comes shortly before the end of the loop shift in the game. This ensures that the first entry is deleted from the parameter list and that the next one takes its place. So all parameters move to the place of $1 and can be processed.

Traps for bash programmers

Bash-Programming is only for the strong-minded - at least until you get used to the peculiarities of the scripting language. Until then, there are a lot of traps lurking for the programmer, including things as banal as variables.

Variable trap I.: When assigned, a variable has no preceding dollar sign, i.e.

However, if the variable is used elsewhere in the program, the dollar sign must be placed in front, i.e.

Variable trap II: When assigning a variable, there must never be a space before or after the equal sign. Who from old programmer habit

writes, has already lost and produces an error. Because it has to look like this:

Error-free bash programming requires the greatest care, but it offers many possibilities for this. (hal)