CS and IT education

This first CDS session is dedicated to courses and tutorials to teach computer science and information technology


Shell programming with Bash for beginners - an introductory course

To solve this problem, we need to sum all integers present in each line of a given input. Each integer can be positive or negative and may have leading or trailing whitespace that needs to be ignored before processing.

Approach

  1. Reading Input : Read each line from the standard input until there are no more lines left.
  2. Splitting Lines into Words : For each line, split it into individual words using shell scripting's tr command to handle any amount of whitespace between words.
  3. Trimming Whitespace : Each word is trimmed to remove any leading or trailing whitespace.
  4. Checking for Valid Integers : Check if the trimmed word matches the pattern of a valid integer (which can be positive, negative, or zero).
  5. Summing Valid Integers : Sum all valid integers found in each line.

Solution Code

text=$(cat <EOF)
while IFS is set; do
  read -r line
  if [ ${line} = ]; then
    break
  fi
  for word in $line; do
    arr+=("$word")
  done
  text=$(cat <EOF | head -n1)
done

sum=0
for i in "${arr[@]}"; do
    trimmed_word=$(echo "$i" | tr '[:space:]' '')
    if [ -z "$trimmed_word" ]; then
        continue
    fi

    if ! [[ "$trimmed_word" =~ ^[+-]?[0-9]+$ ]]; then
        continue
    else:
        sum=$((sum + $trimmed_word))
    fi
done

echo "The sum is: $sum"

Explanation

  1. Reading Input : The input is read line by line using cat <EOF which reads until the end of the file.
  2. Splitting Lines into Words : Each line is processed to split it into words, ignoring any whitespace between them.
  3. Trimming Whitespace : Each word is trimmed to remove any leading or trailing spaces.
  4. Valid Integer Check : Each trimmed word is checked against a regular expression to ensure it represents an integer (including optional sign and digits).
  5. Summing Integers : Valid integers are summed up, starting from zero, and the total sum is printed at the end.

This approach ensures that all valid integers in each line are correctly identified and summed, handling various edge cases such as leading/trailing spaces, multiple spaces between words, and different signs for integers.


Write a detailed tutorial to teach Shell programming with Bash for beginners

Shell Programming with Bash: A Beginner's Tutorial

This tutorial will guide you through the basics of Shell programming with Bash, a powerful scripting language used for automating tasks on Linux and macOS systems. We'll cover fundamental concepts, commands, and best practices to get you started.

What is Bash?

Bash (Bourne Again Shell) is the most common shell used on Linux and macOS. It's an interactive command-line interpreter that allows you to execute commands and scripts. Shell scripting lets you automate repetitive tasks, process data, and manage your system efficiently.

1. Setting Up Your Environment

  • Text Editor: You'll need a text editor to write your scripts. Popular choices include:

  • VS Code: (Recommended - Free, cross-platform)

  • Sublime Text: (Paid, but has a free trial)
  • Nano: (Simple, terminal-based editor)
  • Vim/Emacs: (Powerful but have a steeper learning curve)

  • Terminal: You'll interact with Bash through the terminal. Learn how to open your terminal. On macOS, it's typically found in /Applications/Utilities/Terminal.app . On Linux, it's usually accessible by searching for "Terminal" or "Console".

2. Your First Bash Script

  • Create a File: Create a new file named my_script.sh . It's crucial to use the .sh extension to indicate that it's a Bash script.

  • Add the Shebang: The first line of your script should be the "shebang" which tells the system how to execute the script. For Bash, it's:

bash #!/bin/bash

This line ensures that the script is executed using the Bash interpreter.

  • Add Some Commands: Let's add a simple command to the script:

```bash #!/bin/bash

echo "Hello, world!" ```

This script will print "Hello, world!" to the terminal.

  • Save the File.

3. Running Your Script

  • Make the Script Executable: Before you can run the script, you need to make it executable. Use the chmod command:

bash chmod +x my_script.sh

This command adds execute permission to the script.

  • Run the Script: Now you can execute the script using:

bash ./my_script.sh

The ./ indicates that the script is in the current directory.

You should see "Hello, world!" printed in your terminal.

4. Basic Bash Concepts

  • Commands: Bash commands are instructions that perform specific tasks. Examples: ls , cd , mkdir , rm , echo .

  • Arguments: Commands can take arguments. For example, ls -l uses the -l argument to modify the behavior of the ls command.

  • Variables: Variables store data. You can assign values to variables using the = operator:

bash name="John" echo "Hello, $name!"

The $ symbol is used to access the value of a variable.

  • Control Flow: Bash allows you to control the execution flow of your script using:

  • if statements: Execute commands based on a condition. bash age=25 if [ $age -gt 18 ]; then echo "You are an adult." fi

  • for loops: Repeat a block of code for a set of items. bash for i in 1 2 3 4 5 do echo "Number: $i" done
  • while loops: Repeat a block of code as long as a condition is true. bash count=0 while [ $count -lt 5 ]; do echo "Count: $count" count=$((count + 1)) done

  • Command Substitution: Execute a command and use its output in another command.

bash current_date=$(date +%Y-%m-%d) echo "Today's date is: $current_date"

5. Useful Bash Commands

  • ls : List files and directories.
  • cd : Change directory.
  • mkdir : Create a directory.
  • rm : Remove files or directories (use with caution!).
  • echo : Print text to the terminal.
  • date : Display the current date and time.
  • grep : Search for patterns in files.
  • find : Locate files based on various criteria.
  • sed : Stream editor for text manipulation.
  • awk : Powerful text processing tool.

6. Best Practices

  • Use Comments: Add comments to explain your code. Comments start with # .
  • Use Meaningful Variable Names: Choose descriptive names for your variables.
  • Quote Variables: Always quote variables (e.g., "$name" ) to prevent unexpected behavior, especially when dealing with spaces or special characters.
  • Error Handling: Include error handling in your scripts to gracefully handle unexpected situations.
  • Test Thoroughly: Test your scripts thoroughly before deploying them.

7. Resources for Further Learning

This tutorial provides a foundation for learning Bash scripting. Start with simple scripts and gradually increase the complexity as you gain experience. Practice is key to mastering this powerful scripting language! Good luck!


Write a full tutorial on how to use ip command on Ubuntu Linux

How to Use the ip Command on Ubuntu Linux

The ip command is a versatile tool in Ubuntu Linux for retrieving various network information, including IP addresses, MAC addresses, and network interface details. Below is a structured guide on how to effectively use the ip command.

1. Introduction

The ip command is used to display different types of IP address information based on usage. It can show static IPs, DHCP (Dynamic Host Configuration Protocol) IPs, or all network addresses like link-local and multicast IPs. This command is essential for network management tasks such as checking connectivity, troubleshooting issues, or automating network setup.

2. Basic Usage

To get a quick overview of your IP address:

sudo ip

This will display the version (IPv4 or IPv6) and protocol used (TCP or UDP).


3. Viewing Specific IP Types

Static IP:

If you have a static IP address assigned to your interface.

sudo ip -ipstatic

DHCP IP:

To show the DHCP-assigned IP address:

sudo ip -idhhcp

Link-local IP (for IPv4):

For link-local IPs on IPv4 interfaces:

sudo ip -mlink

4. Getting MAC Address

Retrieve the MAC address of an interface with:

sudo ip addr show | grep -E '^(.*): address ([0-9a-f]{2}-){3}\d+' | cut -d':' -f2 | sed 's/^\s//' || sudo ip addr show | grep -E '(mac)' | cut -d' ' -f1

Alternatively, using the -A option:

sudo ip -A

5. Redirecting Output to a File

Save network information to a file for automation or record-keeping:

sudo ip -i > /root/myips.log

Replace /root/myips.log with your desired file path.


6. Common Use Cases

Checking Interface Status

Use ip link show combined with ifconfig to check which interfaces are up or down.

sudo ip link show | grep -E 'up|down'

For detailed interface information:

sudo ifconfig | grep -E '^Eth.*:.*up'

Network Overview

Combine ip link show with ifconfig to get a network status overview.

sudo ip link show | while read line; do sudo ifconfig "$OPTARG"; done

7. Troubleshooting Issues

Unreachable IP Address

Check for unreachable or invalid IPs:

  • Static IP:
sudo ping -c 3 <static-ip>
  • DHCP IP:
sudo ping -c 3 <dhcp-ip>

Identifying Invalid DHCP IP

To identify an invalid DHCP IP, use the -t option:

sudo ip -idh t=2>/dev/null

Resetting a DHCP-assigned IP:

sudo dhclient --clear InterfaceName # Replace InterfaceName with actual interface name
sudo dhclient $IFNAME

8. Additional Options and Uses

The ip command supports multiple options to fetch specific information, such as interface details or type-specific addresses.

Displaying MAC Address:

sudo ip addr show | grep -E 'address ([0-9a-f]{2}-){3}\d+' | cut -d':' -f2

Multicast IP:

For multicast IPs on IPv4/6:

sudo ip mcast show

Summary

The ip command is a powerful tool for network management in Ubuntu Linux. By using it with various options and flags, you can retrieve detailed information about your IP addresses, MAC addresses, interface statuses, and troubleshoot common networking issues.

For further assistance or troubleshooting specific commands, refer to the Ubuntu Official Documentation .