bash
is the specific implementation of shell that comes preinstalled with most of the linux distributions (distro).
Shell programming offers two primary methods of execution:
- Interactive execution by directly inputting commands at the shell prompt
- Batch execution by storing commands in a shell script file
1 Interactive Execution
When operating interactively, users input commands directly at the shell prompt. The shell immediately interprets and executes each command as it's entered. This method is suitable for executing ad-hoc commands, quickly testing functionality, or performing one-off tasks.
For example:
$ ls
$ mkdir new_directory
$ cd new_directory
2 Shell Script Execution
Shell scripts are text files containing a sequence of shell commands. These scripts are executed by invoking the shell interpreter and passing the script file as an argument.
2.1 Creation of Shell Script
The first line of the shell script begins with a sha-bang
(#!
) which is not read as a comment.
The Shebang Line:
- The shebang line, starting with
#!
, informs the operating system which interpreter should execute the script. It's not treated as a comment but as an instruction. - Following the shebang, the full path to the shell interpreter is specified. This path guides the system to locate the correct interpreter for executing the script.
- For example,
#!/bin/bash
indicates that the script should be interpreted by the Bash shell, which is located at/bin/bash
. - It's crucial to provide the correct path to the interpreter. Otherwise, the system won't be able to locate the interpreter, resulting in a "Command not found" error during script execution.
- You can find your bash shell path (which may vary from the above) using the command:
which bash
Naming Convention:
- While not strictly necessary, it's a common convention to name shell script files with the ".
sh
" extension, which indicates that the file contains shell commands. - This convention helps users quickly identify shell scripts within a directory or project, enhancing readability and organization. However, bash scripts can run perfectly fine without the
sh
extension.
Example:
Here's an example of a shell script file (example_script.sh
) with the shebang line:
#!/bin/bash
# This is a simple shell script
echo "Hello, world!"
2.1 Executing a Shell Script
There are different ways to execute the shell script in the Linux/Unix.
To make the script executable, assign execution rights to your user using this command:
chmod u+x example_script.sh
Here,
chmod
modifies the ownership of a file for the current user:u
.+x
adds the execution rights to the current user. This means that the user who is the owner can now run the script.example_script.sh
is the file we wish to run.
You can run the script using any of the mentioned methods:
sh example_script.sh
bash example_script.sh
./example_script.sh
Bash Basics
1 Shebang Line:
- Always start your Bash script with a shebang line to specify the path to the Bash interpreter.
- Example:
#!/bin/bash
2 Comments:
- Use
#
to add comments for documentation or to annotate your code. - Comments are ignored during script execution.
Example:
#!/bin/bash
# This script greets the user
name="Alice" # Assigning a name to the variable
echo "Hello, $name!" # Printing a greeting message
3 Variables:
- Variables store data that can be used and manipulated within the script.
- Declare variables without spaces around the equal sign (=).
- Access variables using the
$
prefix.
Example:
#!/bin/bash
# This script demonstrates the use of variables
greeting="Hello"
name="Bob"
echo "$greeting, $name!"
4 Input/Output
- Use echo to print messages or variables to the terminal.
- Use read to prompt the user for input.
Example:
echo "What is your name?"
read name
echo "Hello, $name!"
5 Control Structures:
- Use
if
,elif
,else
for conditional branching. - Use
for
andwhile
loops for iteration.
Example:
if [ condition ]; then
# commands
elif [ another_condition ]; then
# more commands
else
# fallback commands
fi
#!/bin/bash
# This script checks if a number is positive, negative, or zero
number=10
if [ $number -gt 0 ]; then
echo "Positive"
elif [ $number -lt 0 ]; then
echo "Negative"
else
echo "Zero"
fi
6 Functions:
- Define reusable blocks of code using functions.
Example:
#!/bin/bash
# This script defines and calls a function
greet() {
echo "Hello, $1!"
}
greet "Carol"
7 Exit Status:
- Commands in Bash scripts return an exit status indicating success or failure.
- Use exit to terminate the script with a specific exit status.
Example:
#!/bin/bash
# This script checks if a file exists
file="example.txt"
if [ -f "$file" ]; then
echo "$file exists."
exit 0 # Success
else
echo "$file does not exist."
exit 1 # Failure
fi
Explanation: This script checks if a file named example.txt exists in the current directory. It exits with status 0 if the file exists and status 1 if it doesn't.
8 File Operations:
- Use commands like touch, mv, cp, rm, mkdir, and cat to manipulate files.
- Use redirection (>, >>, <) and pipes (|) for input/output redirection and chaining commands.
#!/bin/bash
# This script creates a new directory and copies a file into it
mkdir new_directory
cp example.txt new_directory/
echo "File copied successfully."
Explanation: This script creates a new directory named new_directory, copies a file named example.txt into it, and prints a success message.
9 Error Handling:
- Use set -e to exit immediately if any command fails.
- Use trap to catch signals and handle errors gracefully.
#!/bin/bash
# This script demonstrates error handling using set -e
set -e
command_that_might_fail
echo "This line won't be executed if the previous command fails."
Explanation: With set -e, the script exits immediately if any command returns a non-zero exit status. In this example, if command_that_might_fail fails, the script terminates without executing the subsequent commands.
10 Debugging:
- Use echo statements for debugging.
- Use -x option or set -x in the script to enable debug mode.
#!/bin/bash
# This script demonstrates debugging with set -x
set -x
number=5
square=$((number * number))
echo "The square of $number is $square."
set +x
Explanation: With set -x, the script prints each command before executing it. It helps to trace the execution flow and debug issues. set +x turns off the debug mode after the script execution.
Displaying Output
Here we will discuss some methods to receive output from the scripts.
1 Printing to the Terminal:
echo "Hello, World"
This prints the text “Hello, World” to the terminal.
2 Writing to a file:
echo "Text Output to a file." > 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 "Append it" >> output.txt
This appends the text “Append it” 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.
Basic Bash Commands
Here is a list of some of the most commonly used bash commands:
1. ls:
- Lists files and directories in the current directory.
- Example: ls
2. cd:
- Changes the current directory.
- Example: cd /path/to/directory
3. pwd:
Prints the current working directory.
Example: pwd
4. mkdir:
Creates a new directory.
Example: mkdir new_directory
5. touch:
Creates an empty file or updates the access and modification times of an existing file.
Example: touch file.txt
6. cp:
Copies files and directories.
Example: cp file1.txt file2.txt (copies file1.txt to file2.txt)
7. mv:
Moves or renames files and directories.
Example: mv old_file.txt new_file.txt (renames old_file.txt to new_file.txt)
8. rm:
Removes files or directories.
Example: rm file.txt
9. cat:
Concatenates and displays the content of files.
Example: cat file.txt
10. echo:
Prints a message to the terminal.
Example: echo “Hello, world!”
11. grep:
Searches for patterns in files or output.
Example: grep "pattern" file.txt
12. find:
Searches for files and directories in a directory hierarchy.
Example: find /path/to/search -name “filename”
13. chmod:
Changes the permissions of files and directories.
Example: chmod +x script.sh (grants execute permission to script.sh)
14. chown:
Changes the ownership of files and directories.
Example: chown user:group file.txt
15. history:
Displays the command history.
Example: history
16. man:
Displays the manual pages for commands.
Example: man ls
17. alias:
Creates or displays aliases for commands.
Example: alias ll='ls -alF' (creates an alias 'll' for 'ls -alF')
18. wget:
Downloads files from the internet.
Example: wget http://example.com/file.txt
19. tar:
Archives and extracts files.
Example: tar -czvf archive.tar.gz directory
20. ssh:
Connects to a remote server using SSH.
Example: ssh user@hostname