Bash Scripting
#!/bin/bash
# LinuxGuide Bash Utility Script...
# Logs current system info and user message to a file
LOG_FILE="/tmp/linuxguide_log.txt"
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
echo -e "${GREEN}LinuxGuide Bash Utility${NC}"
echo "----------------------------"
# Check if message was passed as argument
if [ -z "$1" ]; then
echo -e "${RED}Error: No message provided.${NC}"
echo "Usage: $0 \"Your message here\""
exit 1
fi
# Create log file if it doesn't exist
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
fi
# Append system info and user message to log
{
echo "----- $(date) -----"
echo "User: $USER"
echo "Uptime: $(uptime -p)"
echo "Message: $1"
echo ""
} >> "$LOG_FILE"
echo -e "${GREEN}Message logged successfully!${NC}"
echo "Log location: $LOG_FILE"
Bash (Bourne Again SHell) is the default shell for most Linux distributions. Learning to write bash scripts allows you to automate repetitive tasks, create custom commands, and build powerful tools. This guide will introduce you to the basics of bash scripting.
Getting Started with Bash Scripts
A bash script is a plain text file containing a series of commands. Here's how to create and run your first script:
1. Create a Script File
Use any text editor to create a file with the .sh extension:
2. Add the Shebang Line
The first line of a bash script should be the shebang, which tells the system which interpreter to use:
3. Add Commands
Add commands to your script:
4. Make the Script Executable
5. Run the Script
Variables in Bash
Variables allow you to store and manipulate data in your scripts:
Conditional Statements
Conditionals allow your scripts to make decisions:
If-Else Statement
Common Test Operators
| Operator | Description | Example |
|---|---|---|
| -eq | Equal to | [ $a -eq $b ] |
| -ne | Not equal to | [ $a -ne $b ] |
| -gt | Greater than | [ $a -gt $b ] |
| -lt | Less than | [ $a -lt $b ] |
| -f | File exists and is a regular file | [ -f $file ] |
| -d | File exists and is a directory | [ -d $directory ] |
Loops
Loops allow you to repeat actions multiple times:
For Loop
While Loop
Functions
Functions allow you to organize your code into reusable blocks: