Scripting in Bash

If you find yourself repeating the same series of commands relatively frequently, it may be idea to make a bash script. A bash script is a simple executable that uses bash as the "programming language."
Creating a bash script

Bash scripts are just text files with the extension ".sh" that begin with the line

#!/bin/bash

After that, the contents of this file are just normal bash commands given line after line. Empty lines do nothing and anything after a "#" will be considered a comment and will not be read during execution.

To call such a script, you can either use "source <bash script>" or first make the script executable with "chmod u+x <bash script>" and then use "./<bash script>" to execute it.
Using Arguments in Bash

If you would like to pass a script arguments on the command line, then you need to use the bash arguments variables $1, $2, $3, etc inside your script to represent them. Where $1 is the first argument, $2 is the second, and so on.
Variables in Bash

Bash is capable of using variables as well. Unlike C++, variables are declared with a type (some examples are given below).

Examples:

mass=500 #mass holds the integer version of 500

mass="500" #mass holds the string, 500

mass=500.0 #mass holds the float version of 500

You can reference a variable in your script by using $. If you wanted to use the value of the variable mass from above, you would need to use ${mass}.
More Information

For more information on how to use bash scripts, such as variables, loops, conditionals, and the like, please use google.

-- ForrestPhillips - 22 Aug 2017
Topic revision: r1 - 22 Aug 2017, ForrestPhillips
 

This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback