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
- Example 1:
- Demonstration
vi ~/myscript.sh
- `echo "Test output"
-
~/myscript.sh
- Fails due to missing +x
-
bash myscript.sh
- Success
chmod +x ~/myscript.sh
-
~/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"
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"