Working with arguments in Bash Scripting

Bash scripting has many special shell variables like $*, $#, $?, etc. to help users write more powerful and versatile scripts. One can code for many scenarios, using these shell variables, which are otherwise not possible.

One of the common requirements is to write a more generic code and run it specifically using the arguments supplied at the run time. Since script users can’t be always trusted with supplying all arguments properly, its beneficial to adjust script to properly check for conditions like how many arguments are supplied, if arguments are proper, etc. Since bash also does not natively offer a way to write parameters for the scripts, you also need to process the arguments in the correct order. For this, bash offers special variables $1, $2$9 as positional parameters.

Read More »

Debug Bash Shell Scripts in Linux

Debugging code can be time consuming and tricky at times. Programmers have traditionally taken advantage of the techniques like syntax highlighting, code completion, intellisense, etc while writing and debugging code. Also no amount of such features can reduce logic based errors, where the script executes but not in a way we expected. This is more problematic with complex bash scripts as bash itself has no support for advanced features like these and most of the sysadmins spend their time with the editors like vi/nano/atom. Sometimes, even simple mistakes like missing a space, can make your scripts fail to run. In this blog post, we’ll discuss some of the common ways to debug bash shell scripts.

Read More »

Testing Bash Script Syntax Before Running

The terminal based editors for bash scripts do not usually point out any errors in bash script syntax. You can often make mistakes when creating a complicated syntax or editing long scripts. It would be good to have bash script checked for syntax before running it or before checking into source control management systems, so as to prevent any last minute issues.

For this issue, we can use bash -n syntax. Let’s see what happens if we run this on a well structured script:

Read More »