Executing Scripts - Paiet/Tech-Journal-for-Everything GitHub Wiki

  • ​Scripts
    • A collection of commands run in order
    • Can be static, or accepts modifiers
  • Executing a script
    • Example 1: bash myscript.sh
      • Interpreter calls the script
    • Example 2: ./myscript.sh
      • Interpreter should be defined on line 1
      • #! /bin/bash
      • Must have execute permissions
  • Demonstration
    1. vi ~/myscript.sh
    2. `echo "Test output"
    3. ~/myscript.sh
      • Fails due to missing +x
    4. bash myscript.sh
      • Success
    5. chmod +x ~/myscript.sh
    6. ~/myscript.sh
      • Success, but missing interpreter may be an issue
  • Variables
    • Many scripts accept input to change their behavior
    • Variables can be populated in the script
    • Variables can be provided via the command line
    • Arguments
      • Variables are populated from the command line
      • Unnamed become $1, $2, etc
      • Can be named
        • NAME="Nicholas"

Variable Examples

Basic Variables

#! /bin/bash
# Syntax: myscript.sh <firstname> <lastname>
HOSTNAME=`hostname`
echo "Firstname: $1"
echo "Lastname: $2"
echo "Full Name: $1 $2"
echo "Shell: $SHELL"
echo "Hostname: $HOSTNAME"
echo "The date is `date`"

Accepting Input

#! /bin/bash
# Syntax: myscript.sh
HOSTNAME=`hostname`
read -p "Enter Firstname: " FNAME
read -p "Enter Lastname: " LNAME
FULLNAME="$FNAME $LNAME"
echo "Firstname: $FNAME"
echo "Lastname: $LNAME"
echo "Full Name: $FULLNAME"
echo "Shell: $SHELL"
echo "Hostname: $HOSTNAME"
echo "The date is `date`"

Performing Arithmetic

NUMBER1=36
NUMBER2=2
let RESULT1=$NUMBER1/$NUMBER2; echo "$NUMBER1/$NUMBER2=$RESULT1"
RESULT2=`expr $NUMBER1 / $NUMBER2`; echo "$NUMBER1/$NUMBER2=$RESULT2"
RESULT3=`echo "$NUMBER1 / $NUMBER2" | bc`; echo "$NUMBER1/$NUMBER2=$RESULT3"
⚠️ **GitHub.com Fallback** ⚠️