# Recitation6
## Topics Today
- Bash scripts
# Bash Scripting Tutorial
## Introduction
Bash scripting is a powerful way to automate tasks and manipulate data on Unix-based systems. In this tutorial, we'll cover the basics of writing Bash scripts and provide an example of using Bash to add numbers from a series of files.
## Writing a Bash Script
Bash scripts are plain text files with a `.sh` extension that contain a sequence of commands. You can create them using any text editor. Here's a basic structure for a Bash script:
```bash=
#!/bin/bash
# This is a comment
```
* `#!/bin/bash` is called a shebang, indicating that this script should be interpreted by the Bash shell.
* `#` denotes comments, which are ignored by the shell and serve to document your code.
## Variables and Input
Bash scripts can use variables and accept inputs. Here's how to declare a variable and read user inputs:
```bash=
#!/bin/bash
# Declare a variable
my_var="Hello, World!"
# Read user input
echo "Enter your name: "
read user_name
echo "Hello, $user_name"
```
### What can echo do?
#### 1. Outputting a Text String
```bash
echo "Hello, World!"
```
This command prints the string "Hello, World!" to the terminal.
#### 2. Outputting the Value of a Variable
```bash
name="Alice"
echo "Hello, $name!"
```
If the value of the variable `name` is "Alice", this command will output "Hello, Alice!".
#### 3. Outputting a String with Special Characters
You can use the `-e` option to enable the interpretation of special characters. For example:
```bash
echo -e "Hello\tWorld!"
```
This will output "Hello" followed by a tab character, then "World!".
#### 4. Outputting to a File
You can use the redirection `>` or `>>` to write the output of `echo` to a file. For example:
```bash
echo "Hello, World!" > myfile.txt
```
This will write the string "Hello, World!" to the file `myfile.txt`. If the file does not exist, bash will create it. If the file already exists, this command will overwrite its content. If you want to append content to the file, you can use `>>`.
#### 5. Not Outputting the Trailing Newline Character
By default, the `echo` command adds a newline character at the end of the output. If you do not want to output this newline character, you can use the `-n` option. For example:
```bash
echo -n "Hello, World!"
```
This will output the string "Hello, World!" without adding a newline character at the end.
#### 6. Displaying an Environment Variable
```bash
echo $HOME
```
This will output the value of the HOME environment variable, which is typically the path to the user's home directory.
#### 7. Displaying All Environment Variables
```bash
echo $(env)
```
This will print all the environment variables and their values.
## Conditional Statements
Bash supports conditional statements like if, elif, and else. Here's a simple example:
```bash=
#!/bin/bash
age=25
if [ $age -lt 18 ]; then
echo "You are a minor."
elif [ $age -ge 18 ] && [ $age -lt 65 ]; then
echo "You are an adult."
else
echo "You are a senior citizen."
fi
```
### How to use?
In Bash scripting, `-lt` and `-ge` are operators used for comparing integer values.
#### -lt
`-lt` stands for "less than." It is used to determine if one integer is less than another.
For example:
```bash
if [ "$a" -lt "$b" ]; then
echo "$a is less than $b"
fi
```
This will print "`a is less than b`" if the value of variable `a` is less than the value of variable `b`.
#### -ge
`-ge` stands for "greater than or equal to." It is used to determine if one integer is greater than or equal to another.
For example:
```bash
if [ "$a" -ge "$b" ]; then
echo "$a is greater than or equal to $b"
fi
```
This will print "`a is greater than or equal to b`" if the value of variable `a` is greater than or equal to the value of variable `b`.
These operators are part of integer comparisons in Bash. Other related operators include:
- `-eq`: equals
- `-ne`: not equal to
- `-gt`: greater than
- `-le`: less than or equal to
## Looping
Bash scripts can use loops like for and while to iterate through data. Here's a for loop example:
```bash=
#!/bin/bash
for fruit in apple banana cherry
do
echo "I like $fruit"
done
```
## Example: Adding Numbers from Files
Here's an example of a simple C program that reads a number `N` from the command line and prints its square:
```c=
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <number>\n", argv[0]);
return 1; // Exit with an error code
}
// Convert the command line argument to an integer
int N = atoi(argv[1]);
// Calculate and print the square
int square = N * N;
printf("%d\n", square);
return 0; // Exit with a success code
}
```
In this program:
- We include the necessary header files for standard input and output (`stdio.h`) and for converting strings to integers (`stdlib.h`).
- We check the number of command line arguments (`argc`). If it's not exactly 2 (the program name and the number), we print a usage message and exit with an error code.
- We use `atoi()` to convert the command line argument (a string) to an integer and store it in the variable `N`.
- We calculate the square of `N` and print the result.
To compile and run the program, save it to a file (e.g., `square.c`), and then compile it using a C compiler like `gcc`:
```bash=
gcc -o square square.c
```
After compiling, you can run the program with a number as a command line argument:
```bash=
./square 5
```
This will print the square of 5:
```bash=
25
```
Certainly! Here's a Bash script that does the following tasks:
1. Runs a C program to calculate the square of numbers from 1 to 100.
2. Creates a folder to store the output files.
3. Redirects the program's output to individual files for each calculation.
4. Reads the numbers from these files and adds them together.
```bash=
#!/bin/bash
# Create a folder to store output files
output_folder="square_output"
mkdir -p "$output_folder"
# Loop through numbers from 1 to 100 and calculate squares
for i in $(seq 1 100); do
./square "$i" > "$output_folder/square_$i.txt"
done
# Initialize a variable to store the sum
total=0
# Loop through the output files and add the numbers
for i in $(seq 1 100); do
file="$output_folder/square_$i.txt"
if [ -f "$file" ]; then
number=$(cat "$file")
total=$((total + number))
fi
done
# Print the total sum
echo "The sum of squares from 1 to 100 is: $total"
# Clean up - remove the output folder and its contents
rm -rf "$output_folder"
```
Save the script to a file (e.g., `calculate_squares.sh`) and make it executable using the following command:
```bash
chmod +x calculate_squares.sh
```
Then, you can run the script to perform the desired tasks:
```bash
./calculate_squares.sh
```
This script will create an `square_output` folder, calculate the squares from 1 to 100, store each result in a separate file, read the numbers from those files, add them together, and finally, print the total sum. Afterward, it cleans up and removes the `square_output` folder.