Tag: Scripting

About Bash

Bash is the GNU Project’s shell. Bash is the Bourne Again SHell. Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard. It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification.https://www.gnu.org/software/bash/

Running Bash on Mac OSX

For this primer we will be using a text editor to write the .sh file and executing them via Terminal. In Finder, search for “Terminal” and select Terminal from Applications.

Running .sh Files via Terminal

The first line contains a shebang #! followed by the path to the shell, in this case bash – this acts as an interpreter directive and ensures that the script is executed under the correct shell.http://ss64.com/osx/syntax-shellscript.html

Open Terminal

Enter chmod u+x {scriptName}.sh and press enter

chmod changes the access permissions

u = User Permission

x = Execute

Enter ./{scriptName}.sh and press enter

dot slash (./) is used in Linux and Unix to execute a compile program in the current directory

You can setup a PATH so that you do not have to enter the dot slash every time

Hello World!

echo
Display message on screen, writes each given STRING to standard output, with a space between each and a newline after the last one.http://ss64.com/bash/echo.html

Open Terminal

Type echo 'Hello World!'

"Hello World!"

Variables

You can use variables as in any programming language. There are no data types. A variable in bash can contain a number, a character, a string of characters.
You have no need to declare a variable, just assigning a value to its reference will create it.http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-5.html

Functions

Like “real” programming languages, Bash has functions, though in a somewhat limited implementation. A function is a subroutine, a code block that implements a set of operations, a “black box” that performs a specified task. Wherever there is repetitive code, when a task repeats with only slight variations in procedure, then consider using a function.http://tldp.org/LDP/abs/html/functions.html

Passing Variables to Functions

Previously, message was accessible because its scope was Global. You can pass variables and values to functions by appending those values to the function call. Also, your function must expect a value. In this example, we pass a string into the function that is assigned a numerical value (the first argument is $1). Use $# to assign the passed in argument to a local variable.

Error Handling

Bash doesn’t have Try…Catch like PowerShell. So, I have tried to frame out how that could be addressed manually. In the example below I pass commands as strings to a Try() function and if that command returns an error it will be caught and addressed in a Catch() function.