BASH SCRIPTING BASICS
No programming language is perfect. There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes. --Herbert Mayer
The default shell in most of todays linux distribution is Bash (Bourne-Again shell). A shell script is a "quick-and-dirty" of completing long and repetitive tasks in linux.
SHEBANG
The first line of a script which start with a #!
is called a shebang. It indicates the interpreter of the script.
#!/bin/bash
In this case the interpreter of the script is bash located in /bin
directory.
MAKE IS EXECUTABLE
It is a practice to keep the extension of the script as .sh
but it actually doesn't matters. What matters is the the executable permission of the script. The Following commands can be used to to make the file executable.
chmod a+x myscript.sh
chmod 755 myscript.sh
WHERE SHOULD IT BE?
To make this script available to all users it has to be in users $PATH
. This can be created in different directories as per requirement.
~/bin/
- users private scripts (~ is the home directory of user)/usr/local/bin
- scripts available to all users on the system/usr/local/sbin
- scripts available to only root on the system
VARIABLES
Defining a variable
CITY=Chicago
a variable CITY
has been created and assigned value "Chicago"
. To use this variable we can use $CITY
or ${CITY}
. If the variable is used in middle of the string where part of the string could be confused as part of variable name, user curly braces. Example:
echo I Live in ${CITY}.${STATE}
SPACES? TAKE CARE
Spaces should not be used before of after the =
sign while assiging a value to a variable.
CITY =Chicago
Script tries to run "CITY"
command with one argument, "=Chicago"
.
CITY= Chicago
Script tries to run "Chicago"
command with the environmental variable "CITY"
set to ""
.
SINGLE OR DOUBLE QUOTES
Quoting preserves white spaces.
CITY="New York"
echo $CITY # prints New York
echo "$CITY" # prints New York
echo '$CITY' # prints $CITY
Single quotes disables variable referencing.
COMMAND SUBSTITUTION
Command substitution reassigns the output of a command or even multiple commands by invoking a subshell. There are 2 ways of using it. Either by using the `backquotes` also known as `backticks` or by using (parentheses). Example:
MYHOSTNAME=`hostname`
or
MYHOSTNAME=$( hostname )
This substitutes the output of command hostname in the variable MYHOSTNAME
.
Like it? Click here to Tweet your feedback