chapter scripts
chapter scripts
The terms "shell" and "bash" are often used interchangeably. But
there is a subtle difference between the two.
The term "shell" refers to a program that provides a command-line
interface for interacting with an operating system. Bash (Bourne-
Again SHell) is one of the most commonly used Unix/Linux shells and
is the default shell in many Linux distributions.
Although Bash is a type of shell, there are other shells available as
well, such as Korn shell (ksh), C shell (csh), and Z shell (zsh). Each
shell has its own syntax and set of features, but they all share the
common purpose of providing a command-line interface for
interacting with the operating system.
You can determine your shell type using the ps command:
ps
# output:
#!/bin/bash
You can find your bash shell path (which may vary from the above) using
the command:
Creating your first bash script
echo -e "\n you path has the following files and folders: "
ls $the_path
2. Writing to a file:
echo "This is some text." > output.txt
This writes the text "This is some text." to a file
named output.txt. Note that the > operator
overwrites a file if it already has some content.
3. Appending to a file:
echo "More text." >> output.txt
This appends the text "More text." to the end of the
file output.txt.
4. Redirecting output:
ls > files.txt
This lists the files in the current directory and writes
the output to a file named files.txt. You can
redirect output of any command to a file this way.
You'll learn about output redirection in detail in
section 8.5.
Conditional statements (if/else)
Expressions that produce a boolean result, either true or false, are
called conditions. There are several ways to evaluate conditions,
including if, if-else, if-elif-else, and nested conditionals.
Syntax:
if [[ condition ]];
then
statement
elif [[ condition ]]; then
statement
else
do this by default
fi
Syntax of bash conditional statements
We can use logical operators such as AND -a and OR -o to make
comparisons that have more significance.
if [ $a -gt 60 -a $b -lt 100 ]
This statement checks if both conditions are true: a is greater
than 60 AND b is less than 100.
Let's see an example of a Bash script that uses if, if-else, and if-elif-
else statements to determine if a user-inputted number is positive,
negative, or zero: