Post

04. Variables and Data Types in Shell Scripting

🚀 Master shell scripting by understanding variables, data types, and operations! Learn about environment vs. local variables, string manipulation, numeric operations, and arrays – empowering you to write efficient and effective shell scripts. 💡

04. Variables and Data Types in Shell Scripting

What we will learn in this post?

  • 👉 Introduction to Shell Variables
  • 👉 Environment vs Local Variables
  • 👉 String Manipulation in Shell
  • 👉 Numeric Operations in Shell
  • 👉 Arrays in Shell Scripting
  • 👉 Conclusion!

Shell Scripting Variables ⭐️

Shell scripting variables are like containers holding information your script needs. Unlike many programming languages, you don’t explicitly declare them with a specific type (like int or string).

Declaring and Assigning Values ✍️

You assign a value to a variable using the = operator. Variable names usually start with a letter.

  • Example:

    1
    2
    
    my_variable="Hello, world!"
    number=10
    

Retrieving Values 👀

To use a variable’s value, simply precede its name with a dollar sign ($).

  • Example:

    1
    2
    
    echo $my_variable  # Prints "Hello, world!"
    echo "The number is: $number" #Prints "The number is: 10"
    

Example Script ✨

1
2
3
4
#!/bin/bash
name="Alice"
age=30
echo "Name: $name, Age: $age"

This script assigns “Alice” to name and 30 to age, then prints them. Easy peasy!

For more in-depth information:

Remember to always use meaningful variable names for better readability! 👍

Environment vs. Local Variables in Shell Scripting 🌎

Let’s explore the differences between environment and local variables in shell scripting! Think of it like this: environment variables are global, affecting your entire shell session, while local variables are confined to a specific script or function.

Environment Variables ✨

Environment variables are available to all processes started within a shell session. They’re set using export.

Common Examples

  • $HOME: Your home directory (e.g., /home/user).
  • $PATH: A list of directories where the system searches for executable commands.
  • $USER: Your username.
1
echo "My home directory is: $HOME"

Local Variables 🛠️

Local variables are defined within a specific script or function. They’re only accessible within that scope.

1
2
my_var="Hello, world!"  #Local Variable
echo "$my_var"

This my_var is only available inside this script. It won’t be accessible in another script or your main shell.

Key Differences Summarized

FeatureEnvironment VariableLocal Variable
ScopeGlobalLocal
AvailabilityAll processesOnly within scope
Settingexport var=valuevar=value

For more information, check out these resources:

Remember, understanding this difference is crucial for writing robust and well-structured shell scripts! 😊

String Manipulation in Shell Scripting 🧵

Shell scripting offers several ways to handle strings. Let’s explore some common techniques!

Concatenation ➕

Concatenating strings is easy using shell parameter expansion:

1
2
3
str1="Hello"
str2=" World!"
echo "${str1}${str2}"  # Output: Hello World!

Substring Extraction ✂️

Shell Parameter Expansion

Extract substrings using parameter expansion:

1
2
str="This is a string"
echo "${str:0:5}" # Output: This
  • "${str:0:5}" extracts 5 characters starting from index 0.

Using cut

The cut command offers another approach:

1
echo "This is a string" | cut -c 1-5 #Output: This

Pattern Replacement 🔄

Using sed

sed is powerful for pattern replacement:

1
echo "Hello World" | sed 's/World/Universe/' # Output: Hello Universe
  • s/World/Universe/ replaces “World” with “Universe”.

Using awk

awk provides more complex pattern matching:

1
echo "apple banana orange" | awk '{gsub(/apple/,"grape"); print}' #Output: grape banana orange
  • gsub(/apple/,"grape") globally replaces “apple” with “grape”.

For more information:

Remember to always quote your variables to prevent word splitting and globbing! Happy scripting! 😊

Shell Arithmetic: expr, let, and $(( )) ➕➖✖️➗

Shell scripting offers several ways to perform arithmetic. Let’s explore three common methods:

Using expr

expr is a command-line utility for evaluating expressions. Note that spaces are crucial around operators.

Examples

  • Addition: expr 5 + 3 (Output: 8)
  • Subtraction: expr 10 - 4 (Output: 6)
  • Multiplication: expr 6 \* 2 (Output: 12) (Note the backslash before the asterisk)
  • Division: expr 15 / 3 (Output: 5)

Using let

let is a built-in shell command. It’s more concise and doesn’t require spaces around operators.

Examples

  • Addition: let "a=5+3"; echo $a (Output: 8)
  • Subtraction: let "b=10-4"; echo $b (Output: 6)
  • Multiplication: let "c=6*2"; echo $c (Output: 12)
  • Division: let "d=15/3"; echo $d (Output: 5)

Using $(( ))

This arithmetic expansion is often the most convenient. It’s embedded directly within the script.

Examples

  • Addition: echo $((5 + 3)) (Output: 8)
  • Subtraction: echo $((10 - 4)) (Output: 6)
  • Multiplication: echo $((6 * 2)) (Output: 12)
  • Division: echo $((15 / 3)) (Output: 5)

For more detailed information and advanced techniques, refer to your shell’s manual pages (e.g., man bash) or online resources.

This method is generally preferred for its readability and simplicity. Choose the method that best suits your coding style and script complexity. Remember to always test your arithmetic expressions to ensure accuracy!

Shell Scripting Arrays 🎉

Shell scripts can use arrays to store multiple values under a single name. Let’s explore!

Indexed Arrays 🔢

Indexed arrays use numerical indices (starting from 0).

Declaration & Manipulation

  • Declare: my_array=("apple" "banana" "cherry")
  • Access: echo ${my_array[1]} (outputs “banana”)
  • Add: my_array+=("date")
  • Length: echo ${#my_array[@]} (outputs 4)

Associative Arrays 📚

Associative arrays use string keys instead of numbers.

Declaration & Manipulation

  • Declare: declare -A my_assoc_array
  • Assign: my_assoc_array["fruit"]="apple"; my_assoc_array["color"]="red"
  • Access: echo ${my_assoc_array["fruit"]} (outputs “apple”)

Iteration with Loops 🔄

Use loops to process array elements:

1
2
3
for i in "${my_array[@]}"; do
  echo "$i"
done

For associative arrays:

1
2
3
for key in "${!my_assoc_array[@]}"; do
  echo "$key: ${my_assoc_array[$key]}"
done

For more detailed information, check out these resources: Bash Guide and Advanced Bash-Scripting Guide

Remember to always quote your array variables ("${my_array[@]}") to handle spaces correctly! 👍

Conclusion

Ta-da! ✨ We’ve reached the end of our journey together. Did we miss anything? Have any brilliant ideas to add? The comments section is your stage! 🎤 We can’t wait to read what you have to say!

This post is licensed under CC BY 4.0 by the author.