Remember that the first value of every command is the command itself. But our script is a file, but not a command right?
Actually, all of our commands are stored as files. It is our PATH variable that determines the directories that the computer looks in for commands that we type.
To run a command (a script file) that isn't in one of the PATH directories - we can add our desired directory to the PATH variable, add our script to an existing command PATH, type the full absolute path to our script, or simply begin our command with a ./ (dot slash) to say "Look for the command in the current directory".
For our purposes the easiest way to test our script is to type
./myscript.sh
Variables
A variable is a placeholder in a script for a value that will be determined when the script runs. Variables' values can be passed as parameters to a script, generated internally to a script, or extracted from a script's environment.
Variable example
#!/bin/bash
#foo.sh
# execute with ./foo.sh arg1 arg2
echo "You just input " $1 $2
Variables within the script
Use the assignment operator to capture the results of something (=), no spaces
ping=/bin/ping
Use the read statement when getting user input
`echo -n "Enter your name "; read name
name variable would store whatever they input
These variables can then be referenced with a $ in front of them.
$ping or $name
Or store the results of a command:
d=$(ls -l foo.txt)
a=ps aux | grep foo
Side note
Variable names can be surrounded by optional curly braces when expanding. Can be useful when a vriable name becomes ambiguous:
filename="myfile"
touch $filename
mv $filename $filename1 #this fails (bash thinks 1 is part of var name)
mv $filename ${filename}1 #this works
Conditional expressions
Do something if something else is true or false.
One common command that uses conditional expressions is if, which allows the system to take one of two actions depending on whether some condition is true.
Example:
if [ -s /tmp/tempstuff ] #see if this file is found
then
echo “/tmp/tempstuff found; aborting!”
exit
fi
More conditionals
if [ condition ]
then
commands
else
other-commands
fi
The test does need to have spaces around the brackets.
This is an excellent resource for learning Bash scripting.
When you've learned the basics of scripting you can write a script in many languages. Just like with any type of programming the only difference is the syntax.