Exploring Bash — Part 9

Dineshkumaar R
8 min readApr 16, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! Let’s dive right in! String manipulation is the process of modifying, combining, and extracting substrings from strings. In Bash scripting, it plays a crucial role in tasks such as parsing log files, processing user input, and formatting output.

Concatenation

String concatenation involves combining multiple strings into a single string. Bash offers multiple ways to concatenate strings, including the concatenation operator (+) and variable interpolation within double quotes.

first_name="Dinesh"
last_name="Kumaar"
full_name="$first_name $last_name"
echo "Full name: $full_name"
#!/bin/bash

# Prompt the user to enter their first name
echo -n "Enter your first name:"
read first_name

# Prompt the user to enter their last name
echo -n "Enter your last name:"
read last_name

full_name="$first_name $last_name"

echo "Full name: $full_name"

Substring Extraction

Substring extraction involves extracting a portion of a string based on specific criteria, such as position or pattern. Bash provides various techniques for extracting substrings, including parameter expansion and substring extraction operators.

#!/bin/bash

string="Hello, world!"
substring="${string:7:5}" # Extracts "world"
echo "Substring: $substring"

1. string=”Hello, world!”: Sets up a variable named string with the value “Hello, world!”.
2. substring=”${string:7:5}”: Extracts a substring from string, starting at index 7 and spanning 5 characters.
3. echo “Substring: $substring”: Prints the extracted substring, preceded by “Substring: “.

String Length

Determining the length of a string is important for various string manipulation tasks. In Bash, you can retrieve the length of a string using the special syntax ${#string}.

#!/bin/bash

string="Hello, world!"
length="${#string}"
echo "Length of the string: $length"

Searching and Replacement

Searching for and replacing substrings within strings is a common string manipulation operation. Bash provides pattern matching and substitution mechanisms for performing search and replace operations.

Syntax

${parameter/pattern/string}

parameter is the variable containing the string.
pattern is the substring or pattern you want to search for.
string is the replacement string.

message="Hello, world!"
new_string="${message/world/Dinesh}"
echo "New string: $new_string" # Outputs "Hello, Dinesh!"

Example 1:

#!/bin/bash

# Define the promotional message with a placeholder for the coupon code
promotional_message="Congratulations! You've won a discount coupon worth \$10. Your coupon code is: [COUPON_CODE]"

# Generate a unique coupon code
generated_coupon=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)

# Replace the placeholder [COUPON_CODE] with the generated coupon code
message_with_coupon="${promotional_message/\[COUPON_CODE\]/$generated_coupon}"

echo "Promotional Message with Generated Coupon Code:"
echo "$message_with_coupon"

• The script initializes a promotional message with a placeholder for the coupon code.
• It generates a unique coupon code consisting of 8 alphanumeric characters.
• The script replaces the placeholder in the promotional message with the generated coupon code.
• Finally, it displays the updated promotional message with the coupon code inserted.

Example 2:

Suppose you have a script that generates a random password, and you want to replace a placeholder in a password policy message with the generated password:

#!/bin/bash

# Define the password policy message with a placeholder password
password_policy="Your new password must contain at least 8 characters: [PASSWORD]"

# Generate a random password
generated_password=$(openssl rand -base64 10)

# Replace the placeholder password with the generated password
policy_with_password="${password_policy/\[PASSWORD\]/$generated_password}"

echo "Password Policy with Generated Password:"
echo "$policy_with_password"

• We define a password policy message with a placeholder [PASSWORD].
• We generate a random password using the openssl rand command.
• We replace the placeholder [PASSWORD] in the password policy message with the generated password.

Splitting

Splitting strings into multiple substrings based on delimiters is useful for processing structured data. In Bash, you can use the ‘IFS’ (Internal Field Separator) variable and the ‘read’ command to split strings into arrays.

#!/bin/bash

paths="/usr/bin:/usr/local/bin:/bin:/sbin"
IFS=':' read -r -a path_array <<< "$paths"
echo "First path: ${path_array[0]}" # Outputs "/usr/bin"

1. Define a variable ‘paths’ with a colon-separated list of paths.
2. Split the ‘paths’ variable into individual paths using the colon (:) separator.
3. Print the first path extracted from the split array.

#!/bin/bash

log_message="2024-04-15 10:23:45 | INFO | User 123 logged in successfully"
IFS='|' read -r -a log_parts <<< "$log_message"

timestamp="${log_parts[0]}"
log_level="${log_parts[1]}"
message="${log_parts[2]}"

echo "Timestamp: $timestamp"
echo "Log Level: $log_level"
echo "Message: $message"

• Assign a log message to the variable log_message.
• Split the log message using the pipe character (|) as the delimiter and store the parts in the log_parts array.
• Extract the timestamp from the first part of the split log message and store it in the variable timestamp.
• Extract the log level from the second part of the split log message, considering the second word as the log level, and store it in the variable log_level.
• Extract the message from the third part of the split log message and store it in the variable message.
• Output the extracted timestamp.
• Output the extracted log level.
• Output the extracted message.

Case Conversion

Case conversion refers to the process of changing the case (uppercase or lowercase) of characters within a string. This operation is commonly used in text processing tasks for various purposes, such as data normalization, formatting, or matching.

In Bash scripting, case conversion can be achieved using various methods:

1.Parameter expansion: Bash provides built-in parameter expansion operators like ${var,,} for converting a variable var to lowercase and ${var^^} for converting it to uppercase.
2.External commands: Utilities like tr, awk, and sed can also be used for case conversion, although they involve calling external processes.

Example 1:

#!/bin/bash

string="Learning Bash is very easy"

lowercase="${string,,}"
uppercase="${string^^}"

echo "Lowercase: $lowercase"
echo "Uppercase: $uppercase"

Example 2:

#!/bin/bash

string="Learn Bash and automate Scripts"

uppercase1=$(echo "$string" | tr '[:lower:]' '[:upper:]')
echo "Uppercase using 'tr': $uppercase1"

uppercase2=$(echo "$string" | awk '{print toupper($0)}')
echo "Uppercase using 'awk': $uppercase2"

uppercase3=$(echo "$string" | sed 's/.*/\U&/')
echo "Uppercase using 'sed': $uppercase3"

1. Using ‘tr’ (Translate):
— ‘tr’ is a command-line utility for translating or deleting characters.
— In this method, it translates all lowercase characters to uppercase in the string.

2. Using ‘awk’ (Awkward):
— ‘awk’ is a versatile text-processing tool that processes data line by line.
— In this method, ‘toupper($0)’ is used to convert each line to uppercase.

3. Using ‘sed’ (Stream Editor):
— ‘sed’ is a powerful stream editor for filtering and transforming text.
— In this method, ‘s/.*/\U&/’ substitutes the entire line (.*) with its uppercase version (\U&).

String Comparison

String comparison operations allow you to compare strings for equality or determine their relative order. In Bash, you can use the `==` operator for string equality and `<`, `>`, `<=`, `>=` operators for string comparison.

Example 1:

#!/bin/bash

string1="orange"
string2="banana"
if [ "$string1" \< "$string2" ]; then
echo "$string1 comes before $string2"
else
echo "$string1 comes after $string2"
fi

This script compares two strings, string1 and string2, and determines their lexicographical order. If string1 comes before string2 in lexicographical order (meaning it would appear first in a dictionary), it prints a message indicating that. Otherwise, it prints a message indicating that string1 comes after string2.

Example 2:

#!/bin/bash

# Check password strength
read -p "Enter your password: " entered_password

if [ "${#entered_password}" -ge 8 ] && [[ "$entered_password" =~ [A-Z] ]] && [[ "$entered_password" =~ [0-9] ]]; then
echo "Password is strong."
else
echo "Password is weak. It should be at least 8 characters long and contain at least one uppercase letter and one digit."
fi

1. Prompt for Password: The script asks the user to input a password by displaying the message “Enter your password: ”.

2. Check Password Strength:
— Length Check: It checks if the length of the entered password is 8 characters or more using ${#entered_password}.
— Uppercase Letter Check: It verifies if the password contains at least one uppercase letter using [[ “$entered_password” =~ [A-Z] ]].
— Digit Check: It confirms if the password contains at least one digit using [[ “$entered_password” =~ [0–9] ]].

3. Output Result:
— If the password meets all these criteria, it prints “Password is strong.”
— If the password fails any of the criteria, it prints “Password is weak. It should be at least 8 characters long and contain at least one uppercase letter and one digit.”

Example 3:

#!/bin/bash

# Check file extension
read -p "Enter file_name with extension:" file_name

supported_extensions=("pdf" "doc" "docx" "txt")
file_extension="${file_name##*.}"

if [[ " ${supported_extensions[@]} " =~ " ${file_extension} " ]]; then
echo "File format is supported."
else
echo "Unsupported file format."
fi

Prompt for File Name:

read -p “Enter file_name with extension:” file_name: This line prompts the user to enter the name of a file, including its extension. The input is stored in the variable file_name.

Define Supported Extensions:

supported_extensions=(“pdf” “doc” “docx” “txt”): This line creates an array named supported_extensions containing the supported file extensions.

Extract File Extension:

file_extension=”${file_name##*.}”: This line uses parameter expansion to extract the file extension from the input file_name and stores it in the variable file_extension.

Check if File Extension is Supported:

[[ “ ${supported_extensions[@]} “ =~ “ ${file_extension} “ ]]: This line checks if the extracted file extension (file_extension) is present in the array of supported extensions (supported_extensions).

If the file extension is found in the array, it means the file format is supported, and the script echoes “File format is supported.”

If the file extension is not found, it means the file format is not supported, and the script echoes “Unsupported file format.”

Summary of the blog

1. Concatenation: Combining strings using concatenation operators or variable interpolation.
2. Substring Extraction: Extracting substrings based on specific criteria like position or pattern.
3. String Length: Determining the length of a string using ${#string}.
4. Searching and Replacement: Performing search and replace operations within strings using pattern matching and substitution.
5. Splitting: Splitting strings into substrings based on delimiters using IFS and read.
6. Case Conversion: Changing the case of characters within a string to either uppercase or lowercase.
7. String Comparison: Comparing strings for equality or determining their relative order using operators like ==, <, >, etc.

URL’s :

  1. Exploring bash — Part1 : https://medium.com/@dineshkumaar478/exploring-bash-part-1-3dabf4b5ef9e
  2. Exploring bash — Part2 : https://medium.com/@dineshkumaar478/exploring-bash-part-2-71f341fb5700
  3. Exploring bash — Part3 : https://medium.com/@dineshkumaar478/exploring-bash-part-3-db1fc958eb17
  4. Exploring bash — Part4 : https://medium.com/@dineshkumaar478/exploring-bash-part-4-4521aaac30ea
  5. Exploring bash — Part5 : https://medium.com/@dineshkumaar478/exploring-bash-part-5-a136eb036b4f
  6. Exploring bash — Part6 : https://medium.com/@dineshkumaar478/exploring-bash-part-6-31887f5c3695
  7. Exploring bash — Part7 : https://medium.com/@dineshkumaar478/exploring-bash-part-7-f9a3e37a5931
  8. Exploring bash — Part8 : https://medium.com/@dineshkumaar478/exploring-bash-part-8-fa6fbb538d3a

Thank you for taking the time to read my blog. Wishing you a joyful learning experience ahead!

--

--

Dineshkumaar R

🔐 Cyber Security Engineer | Penetration Tester | VAPT Specialist | 🚩 Hackthebox (Pro Hacker) | 🏆 Tryhackme (Guru)