Introduction to Bash Shell Scripting and Syntax

Introduction to Shell Scripting

  • A script is defined as a short program designed to perform a specific, targeted task. It consists of a series of commands combined into a single executable file.

  • A shell script is a script that is executed specifically by a command-line shell.

  • Most shells, including bash, possess a built-in syntax for writing script programs.

  • There is a threshold for script complexity: if a script exceeds approximately 100100 to 150150 lines of code, it is recommended to switch to a more robust programming language.

  • The general workflow for writing a bash script involves:

    • Typing one or more commands into a file and saving it.

    • Including a special header at the top of the file to identify the interpreter.

    • Enabling execute permissions on the file.

    • Running the file.

Basic Script Syntax and Components

  • The first line of an executable script must be the shebang or interpreter directive, written as #!interpreter. This line dictates which interpreter will run the commands in the script.

  • The standard interpreter for these scripts is /bin/bash.

  • Example of a basic script that removes output files and lists current files:

    • #!/bin/bash

    • rm output*.txt

    • ls -l

Executing Shell Scripts

  • There are three primary methods to run a shell script:

    • Making it Executable (Recommended): Use the command chmod u+x myscript.sh and run it with ./myscript.sh. This process forks a new process, executes the commands, and then exits.

    • Launching a New Shell: Use the command bash myscript.sh. The advantage of this method is that it can run without execute permissions, though read permissions are still required.

    • Running Within the Current Shell: Use the command source myscript.sh. This is advantageous because any variables defined within the script will remain available in the current shell session after execution.

Scripting Logic and Commands

  • The echo Command: This command produces its parameters as output, functioning similarly to println in other languages.

    • The -n flag can be used to remove the trailing newline character, allowing it to function like a standard print statement.

  • Exercise: Write a script for the attu system that clears the screen, displays the date and time, and shows currently logged-on users along with processor info.

  • Script Example Implementation:

    • #!/bin/bash

    • clear

    • echo "Today's date is $(date)"

    • echo

    • echo "These users are currently connected:"

    • w -h | sort

    • echo

    • echo "This is $(uname -s) on a $(uname -m) processor."

    • echo

    • echo "This is the uptime information:"

    • uptime

    • echo

    • echo "That's all folks!"

Shell Comments

  • Bash supports only single-line comments using the # symbol. There is no equivalent to multi-line comment blocks like /* ... */ seen in other languages.

  • Example of comments in usage:

    • #!/bin/bash

    • # Leonard's first script ever

    • # by Leonard Linux

    • echo "This is my amazing script!"

    • echo "The time is: $(date)" # This is the part where I print my current directory

    • echo "Current dir is: (pwd)"</code></p></li></ul></li></ul><h3id="99faed4d−6650−4d12−93b2−6f0fa57514b8"data−toc−id="99faed4d−6650−4d12−93b2−6f0fa57514b8"collapsed="false"seolevelmigrated="true">ShellVariablesandDataHandling</h3><ul><li><p><strong>Declaration:</strong>Variablesaredeclaredusingthesyntax<code>name=value</code>.</p><ul><li><p>Crucially,theremustbenospacesaroundtheequalssign.</p></li><li><p>Byconvention,variablenamesareoftenwritteninall−uppercaseletters.</p></li><li><p>Onceavariableisset,itremainsinscopeuntilitisunsetwithinthecurrentshell.</p></li><li><p>Example:<code>AGE=64</code>and<code>NAME="MichaelYoung"</code>.</p></li></ul></li><li><p><strong>Usage:</strong>Variablesareaccessedusingthe<code>(pwd)"</code></p></li></ul></li></ul><h3 id="99faed4d-6650-4d12-93b2-6f0fa57514b8" data-toc-id="99faed4d-6650-4d12-93b2-6f0fa57514b8" collapsed="false" seolevelmigrated="true">Shell Variables and Data Handling</h3><ul><li><p><strong>Declaration:</strong> Variables are declared using the syntax <code>name=value</code>.</p><ul><li><p>Crucially, there must be no spaces around the equals sign.</p></li><li><p>By convention, variable names are often written in all-uppercase letters.</p></li><li><p>Once a variable is set, it remains in scope until it is unset within the current shell.</p></li><li><p>Example: <code>AGE=64</code> and <code>NAME="Michael Young"</code>.</p></li></ul></li><li><p><strong>Usage:</strong> Variables are accessed using the <code> prefix before the name.

      • Example: echo "$NAME is $AGE years old" outputs Michael Young is 64 years old.

    Common Errors in Variable Management

    • Misspelling: If a variable name is misspelled during assignment (e.g., Name=Rob instead of NAME=Rob), bash will simply create a new variable rather than updating the intended one.

    • Undeclared Variables: Using a variable that has not been defined results in an empty value rather than an error (e.g., echo "Welcome, $name" results in Welcome,).

    • Multi-word Strings: When storing strings containing spaces, double quotes must be used. NAME=Ruth Anderson will fail, while NAME="Ruth Anderson" correctly assigns the value.

    • The $ Prefix during Assignment: Using the $ symbol when assigning or reassigning a variable is an error. mystring="Hithere"mystring="Hi there" is incorrect; only use the name for the target of an assignment.

    • Forgetting echo: If you type $name instead of echo $name, the shell will attempt to execute the value of the variable as a command.

    Command Output Capture and Quotation Mechanics

    • Output from a command can be captured into a variable using the syntax variable=(command)</code>.</p><ul><li><p>Simpleexample:<code>FILE=(command)</code>.</p><ul><li><p>Simple example: <code>FILE=(ls *.txt).

    • Complex example: FILE=(ls−1∗.txt∣sort∣tail−n1)</code>.</p></li></ul></li><li><p><strong>Doublevs.SingleQuotes:</strong></p><ul><li><p><strong>DoubleQuotes:</strong>Variablenamesareexpandedandcommandswithin<code>(ls -1 *.txt | sort | tail -n 1)</code>.</p></li></ul></li><li><p><strong>Double vs. Single Quotes:</strong></p><ul><li><p><strong>Double Quotes:</strong> Variable names are expanded and commands within <code>() are executed.

      • Example: "Hi $NAME! Today is $(date)" expands to include the variable value and current date.

    • Single Quotes: These treat all characters literally. Variables are not expanded, and commands in $() are not performed.

      • Example: 'Hi $NAME! Today is (date)′</code>printsexactlythatstring.</p></li></ul></li><li><p><strong>BestPractice:</strong>Itisconsideredgoodpracticetowrapvariablereferencesindoublequoteswhenusingthem.</p></li></ul></li></ul><h3id="74a0ffa1−1d07−4147−aa78−e7758bcfc27c"data−toc−id="74a0ffa1−1d07−4147−aa78−e7758bcfc27c"collapsed="false"seolevelmigrated="true">IntegerOperationsandProgrammingComparisons</h3><ul><li><p>Bashvariablesareprimarilystoredasstrings.Standardoperationsareperformedasstringmanipulationsbydefault.</p></li><li><p>Toperformmathematicalintegeroperations,the<code>let</code>commandisused.</p><ul><li><p>Example:<code>x=42</code>,<code>y=15</code>,<code>letz="(date)'</code> prints exactly that string.</p></li></ul></li><li><p><strong>Best Practice:</strong> It is considered good practice to wrap variable references in double quotes when using them.</p></li></ul></li></ul><h3 id="74a0ffa1-1d07-4147-aa78-e7758bcfc27c" data-toc-id="74a0ffa1-1d07-4147-aa78-e7758bcfc27c" collapsed="false" seolevelmigrated="true">Integer Operations and Programming Comparisons</h3><ul><li><p>Bash variables are primarily stored as strings. Standard operations are performed as string manipulations by default.</p></li><li><p>To perform mathematical integer operations, the <code>let</code> command is used.</p><ul><li><p>Example: <code>x=42</code>, <code>y=15</code>, <code>let z="x + $y" results in z=57z = 57.

      • Supported integer operators include addition +, subtraction -, multiplication *, division /, and modulo %.

      • The bc command can be utilized for more complex mathematical expressions.

      • If a non-numeric variable is used in a numeric context (via let), its value is treated as 00.

    • Comparison with Java:

      • In Java, String s = "hello"; corresponds to s=hello in Bash.

      • In Java, System.out.println(s); corresponds to echo s</code>inBash.</p></li><li><p>ConcatenationinJava<code>s=s+"s";</code>isachievedinBashvia<code>s=s</code> in Bash.</p></li><li><p>Concatenation in Java <code>s = s + "s";</code> is achieved in Bash via <code>s={s}s.

      • Integer parsing and addition in Java int n = Integer.parseInt(s2) + Integer.parseInt(s3); is achieved in Bash via let n="$s2 + $s3".

    Built-in Shell Variables and Environment Configuration

    • Several special variables are automatically defined in every bash session:

      • DISPLAY</code>:SpecifiesthelocationforgraphicalX−windowsoutput.</p></li><li><p><code>DISPLAY</code>: Specifies the location for graphical X-windows output.</p></li><li><p><code>HOSTNAME: The name of the computer currently in use.

      • HOME</code>:Theuser′shomedirectorypath.</p></li><li><p><code>HOME</code>: The user's home directory path.</p></li><li><p><code>PATH: A list of directories searched by the shell to find executable commands.

      • PS1</code>:Thestringdefiningtheshell′scommandprompt.</p></li><li><p><code>PS1</code>: The string defining the shell's command prompt.</p></li><li><p><code>PWD: The current working directory.

      • SHELL</code>:Thefullpathtothecurrentshellprogram.</p></li><li><p><code>SHELL</code>: The full path to the current shell program.</p></li><li><p><code>USER: The current login username.

    • The PATHVariable:</strong>Whenacommandisentered,theshellsearchesthedirectorieslistedin<code>PATH Variable:</strong> When a command is entered, the shell searches the directories listed in <code>PATH. Users can modify this to include custom script directories: PATH=$PATH:/homes/iws/rea.

    Variable Persistence and Visibility

    • Management Commands:

      • set: Displays all variables (not typically needed for assignment, as x=3 suffices).

      • unset: Deletes a variable and its associated value.

      • export: Sets a variable and ensures it is inherited by any child processes or programs launched by the current shell.

      • readonly: Marks a variable so it cannot be modified by programs launched from that shell.

    • Exercise: Setting a local variable and launching a new bash shell will show the variable is not visible unless export is used before launching the new shell.

    Console and Command-line Input/Output

    • Values read from the console are always stored as strings.

    • Shell Commands for I/O:

      • read: Takes input from the console and stores it in a variable. The -p flag acts as a prompt.

      • echo: Outputs text to the console.

      • printf: Outputs formatted text to the console (e.g., printf "%10s is %4s years old" $name $age).

    • Command-line Arguments: Accessing arguments passed when starting a script:

      • $0: The name of the script itself.

      • $1, $2, 3,...</code>:Theindividualargumentsprovided.</p></li><li><p><code>3, ...</code>: The individual arguments provided.</p></li><li><p><code>#: Total number of arguments provided.

      • @</code>:Anarray−likeobjectcontainingallarguments.</p></li></ul></li></ul><h3id="2462c286−2a90−47b0−99d7−200bce2b0a16"data−toc−id="2462c286−2a90−47b0−99d7−200bce2b0a16"collapsed="false"seolevelmigrated="true">ControlStructures:TheForLoop</h3><ul><li><p><strong>Syntax:</strong></p><ul><li><p><code>fornameinvalue1value2...valueN;do</code></p></li><li><p><code>commands</code></p></li><li><p><code>done</code></p></li></ul></li><li><p>Notethatasemicolonisrequiredafterthelistofvaluesif<code>do</code>isonthesameline.</p></li><li><p>Thevaluesprovidedtotheloopcanbehard−coded,asetoffilenameresults,orthespecialargumentvariable<code>@</code>: An array-like object containing all arguments.</p></li></ul></li></ul><h3 id="2462c286-2a90-47b0-99d7-200bce2b0a16" data-toc-id="2462c286-2a90-47b0-99d7-200bce2b0a16" collapsed="false" seolevelmigrated="true">Control Structures: The For Loop</h3><ul><li><p><strong>Syntax:</strong></p><ul><li><p><code>for name in value1 value2 ... valueN; do</code></p></li><li><p><code>commands</code></p></li><li><p><code>done</code></p></li></ul></li><li><p>Note that a semicolon is required after the list of values if <code>do</code> is on the same line.</p></li><li><p>The values provided to the loop can be hard-coded, a set of filename results, or the special argument variable <code>@.

      • Loop Examples:

        • Looping over colors: for val in red blue green; do echo "val is: $val"; done.

        • Looping over arguments: for val in $@; do echo "val is: $val"; done.

        • Using the seq command: for val in $(seq 4); do echo "val is: $val"; done generates a sequence from 11 to 44.

        • File processing: for file in *.txt; do mv $file ${file}2; done renames all text files to have a .txt2 extension.

      Practical Application: createhw.sh

      • Task: Create a script named createhw.sh that generates a series of homework directories (hw1, hw2, etc.) up to a maximum number specified by a command-line argument. Within each directory, a file criteria.txt should be copied and renamed to criteria(2*i).txt, and a script.sh file should be copied and executed.

      • Complete Script Solution:

        • #!/bin/bash

        • # Creates directories for a given number of assignments.

        • for num in $(seq $1); do

        • let CRITNUM="2 * num"</code></p></li><li><p><code>mkdir"hwnum"</code></p></li><li><p><code>mkdir "hwnum"

        • cp script.sh "hwnum/"</code></p></li><li><p><code>cpcriteria.txt"hwnum/"</code></p></li><li><p><code>cp criteria.txt "hwnum/criteriaCRITNUM.txt"</code></p></li><li><p><code>echo"CreatedhwCRITNUM.txt"</code></p></li><li><p><code>echo "Created hwnum."

        • cd "hw$num/"

        • bash ./script.sh

        • cd ..

        • done

      • This script demonstrates the use of command-line arguments ($1), the seq command, the let command for arithmetic, and directory navigation within loops.