Executing a Bash Script with Multivariables in Linux

Avatar

By squashlabs, Last Updated: Oct. 22, 2023

Executing a Bash Script with Multivariables in Linux

Passing Multiple Variables to a Bash Script

Bash scripts can accept command-line arguments, which allow you to pass data to the script when executing it. These arguments can be accessed within the script using special variables.

The arguments passed to a script are stored in the variables $1, $2, $3, and so on, where $1 represents the first argument, $2 represents the second argument, and so on. The variable $0 contains the name of the script itself.

Here's an example:

#!/bin/bash

echo "The first argument is: $1"
echo "The second argument is: $2"
echo "The third argument is: $3"

If we execute this script with the command bash script.sh foo bar baz, the output will be:

The first argument is: foo
The second argument is: bar
The third argument is: baz

If fewer arguments are passed than the number of variables used, the remaining variables will be empty.

Related Article: Tutorial on Traceroute in Linux

Command Line Arguments in Bash Scripts

In addition to the positional parameters ($1, $2, etc.), Bash provides several special variables that can be used to access command line arguments and other information about the script's execution.

- $#: Contains the number of arguments passed to the script.

- $@: Expands to all the arguments passed to the script as separate words.

- $*: Expands to all the arguments passed to the script as a single word, separated by spaces.

- $?: Contains the exit status of the last command.

- $$: Contains the process ID of the script.

- $!: Contains the process ID of the last background command.

Here's an example that demonstrates the usage of these variables:

#!/bin/bash

echo "Number of arguments: $#"
echo "All arguments: $@"
echo "Arguments as a single word: $*"
echo "Exit status of the last command: $?"
echo "Process ID of the script: $$"
echo "Process ID of the last background command: $!"

If we execute this script with the command bash script.sh foo bar baz, the output will be:

Number of arguments: 3
All arguments: foo bar baz
Arguments as a single word: foo bar baz
Exit status of the last command: 0
Process ID of the script: 12345
Process ID of the last background command:

Note that the last variable, $!, is empty because we didn't execute any background commands.

Parameter Passing in Bash Scripts

In Bash, you can pass parameters to a function or script using two different mechanisms: positional parameters and environment variables.

Positional parameters are variables that are automatically assigned the values of the command-line arguments. They are accessed using the $1, $2, etc. syntax, where $1 represents the first argument, $2 represents the second argument, and so on.

Here's an example that demonstrates the usage of positional parameters:

#!/bin/bash

function greet {
    echo "Hello, $1!"
}

greet "John"

When executing this script, the output will be:

Hello, John!

In this example, the greet function takes one argument, which is accessed using $1 within the function.

Environment variables, on the other hand, are variables that are set in the shell environment and can be accessed by any script or program running in that environment. Environment variables are accessed using the $VAR_NAME syntax, where VAR_NAME is the name of the variable.

Here's an example that demonstrates the usage of environment variables:

#!/bin/bash

echo "Home directory: $HOME"
echo "Current user: $USER"

When executing this script, the output will be:

Home directory: /home/john
Current user: john

In this example, the $HOME and $USER environment variables are accessed within the script.

Functions in Bash Scripts

Functions in Bash scripts allow you to group a set of commands together and give them a name. This makes your script more modular and easier to read and maintain.

To define a function, you can use the following syntax:

function function_name {
    # function body
}

Here's an example that defines a function named greet:

#!/bin/bash

function greet {
    echo "Hello, World!"
}

greet

When executing this script, the output will be:

Hello, World!

In this example, the greet function is defined to print the string "Hello, World!". The function is then called at the end of the script.

You can pass arguments to a function by specifying them within the parentheses after the function name. The arguments can be accessed within the function using the $1, $2, etc. syntax.

Here's an example that demonstrates the usage of function arguments:

#!/bin/bash

function greet {
    echo "Hello, $1!"
}

greet "John"

When executing this script, the output will be:

Hello, John!

In this example, the greet function takes one argument, which is accessed using $1 within the function.

Related Article: How to Limi Argument Inputs in Bash Scripts

Parameter Expansion in Bash Scripts

Parameter expansion is a useful feature in Bash that allows you to manipulate the values of variables and perform various operations on them.

Here are some commonly used parameter expansion techniques:

- ${variable}: Retrieves the value of the variable.

- ${variable:-default}: Uses the value of the variable, or the default value if the variable is unset or empty.

- ${variable:=default}: Uses the value of the variable, or assigns the default value to the variable if it is unset or empty.

- ${variable:+alternate}: Uses the alternate value if the variable is set and not empty, otherwise uses an empty string.

- ${variable:?error_message}: Displays an error message and exits the script if the variable is unset or empty.

- ${variable#pattern}: Removes the shortest match of pattern from the beginning of the variable's value.

- ${variable##pattern}: Removes the longest match of pattern from the beginning of the variable's value.

- ${variable%pattern}: Removes the shortest match of pattern from the end of the variable's value.

- ${variable%%pattern}: Removes the longest match of pattern from the end of the variable's value.

- ${variable/pattern/replacement}: Replaces the first match of pattern with replacement in the variable's value.

- ${variable//pattern/replacement}: Replaces all matches of pattern with replacement in the variable's value.

Here's an example that demonstrates the usage of parameter expansion:

#!/bin/bash

name="John"
echo "Hello, ${name:-Anonymous}!"

When executing this script, the output will be:

Hello, John!

In this example, we use the ${name:-Anonymous} parameter expansion to check if the name variable is unset or empty. If it is, the default value "Anonymous" is used instead.

Calling a Script with Multiple Arguments

To call a script with multiple arguments, you simply separate the arguments with spaces when executing the script.

Suppose we have a Bash script named script.sh with the following content:

#!/bin/bash

echo "The first argument is: $1"
echo "The second argument is: $2"
echo "The third argument is: $3"

To call this script with multiple arguments, you can run the following command:

$ bash script.sh foo bar baz

The output will be:

The first argument is: foo
The second argument is: bar
The third argument is: baz

In this example, we pass three arguments (foo, bar, baz) to the script, which are then accessed using $1, $2, $3.

Handling Parameters in Bash Scripts

When working with parameters in Bash scripts, it is important to handle edge cases such as checking for the presence or absence of certain arguments, handling default values, and validating the input.

Here's an example that demonstrates how to handle parameters in a Bash script:

#!/bin/bash

if [[ -z $1 ]]; then
    echo "No argument provided."
    exit 1
fi

filename="$1.txt"
echo "Creating file: $filename"
touch "$filename"

In this example, we check if the first argument is empty using the -z conditional expression. If it is empty, we print an error message and exit the script with a non-zero exit code. Otherwise, we create a new file with the name provided as the first argument.

This is just a basic example, but in real-world scenarios, you may need to handle more complex parameter validations and error handling.

Executing a Script with Multiple Variables from Another Script

In Bash, you can execute a script with multiple variables from another script by passing the values to the script as command-line arguments.

Suppose we have a Bash script named script.sh with the following content:

#!/bin/bash

echo "The first variable is: $1"
echo "The second variable is: $2"
echo "The third variable is: $3"

To execute this script with multiple variables from another script, you can use the following syntax:

#!/bin/bash

variable1="foo"
variable2="bar"
variable3="baz"

bash script.sh "$variable1" "$variable2" "$variable3"

When executing the script, the output will be:

The first variable is: foo
The second variable is: bar
The third variable is: baz

In this example, we define three variables (variable1, variable2, variable3) in the calling script and pass their values as command-line arguments to the script.sh script.

Related Article: How to Make a Bash Script Continue to Run After an Error

Best Practices for Handling Variables in Bash Scripts

When working with variables in Bash scripts, it is important to follow some best practices to ensure your scripts are reliable, maintainable, and secure.

1. Use descriptive variable names: Choose meaningful names for your variables that accurately describe their purpose or content. This makes your code more readable and easier to understand.

2. Use proper variable scoping: Declare your variables in the appropriate scope to prevent unintended side effects. Local variables should be declared within functions, while global variables should be declared outside of any function.

3. Initialize variables before use: Always initialize your variables before using them to avoid unexpected behavior. Uninitialized variables can lead to errors or produce incorrect results.

4. Quote variable expansions: When expanding variables, always wrap them in double quotes ("$variable") to prevent word splitting and pathname expansion. This ensures that the variable is treated as a single entity and preserves any special characters.

5. Avoid using global variables unless necessary: Global variables can introduce complexity and make your code more error-prone. Whenever possible, use local variables within functions to encapsulate data and prevent unintended changes.

6. Validate and sanitize user input: When accepting user input as variables, validate and sanitize the input to prevent security vulnerabilities such as code injection or unexpected behavior.

7. Use variable substitution and parameter expansion: Take advantage of Bash's useful features for manipulating variables, such as parameter expansion, to simplify your code and make it more efficient.

8. Document your variables: Include comments or documentation to explain the purpose and usage of your variables. This helps other developers (including yourself) understand the code and its intended behavior.

Proper Variable Substitution in a Bash Script

In Bash, proper variable substitution is important to ensure that the correct value is substituted and that any special characters or spaces within the value are handled correctly.

To substitute a variable in Bash, you can use the $variable syntax. However, there are cases where you need to use special syntax for proper substitution.

Here are some common scenarios and how to handle them:

- When substituting a variable within a string, it is recommended to enclose the variable name in curly braces to avoid ambiguity. For example:

#!/bin/bash

name="John"
echo "Hello, ${name}!"

- When using variables within command substitutions (enclosing a command within $()), it is important to quote the command substitution to preserve any whitespace or special characters. For example:

#!/bin/bash

files=$(ls *.txt)
echo "Files: $files"

- When performing arithmetic operations with variables, you can use the $(( )) syntax. This ensures that the result of the arithmetic operation is substituted correctly. For example:

#!/bin/bash

num1=10
num2=5
result=$((num1 + num2))
echo "Result: $result"

- When substituting variables in a command that requires quoting or escaping, it is recommended to use quotes or backslashes appropriately. For example:

#!/bin/bash

path="/path/with spaces"
echo "Path: \"$path\""

These are just a few examples of proper variable substitution in Bash. It is important to understand the specific requirements and syntax of each scenario to ensure correct and reliable substitution.

Additional Resources



- Passing Multiple Arguments to a Bash Script

- Command Line Arguments in Bash Script with Multiple Variables

How to Filter Strings in Bash Scripts

Pattern-based string filtering is a powerful technique that can greatly enhance your Linux bash scripting skills. In this article, you will learn how… read more

How to Extract Substrings in Bash

Extracting substrings in bash can be a powerful tool for manipulating text and data. In this guide, we will explore different methods to extract subs… read more

Appending Dates to Filenames in Bash Scripts

Learn how to append dates to filenames in Linux bash scripts with this concise tutorial. Discover the steps to add the current date to file names usi… read more

Using SSH to Connect to a Remote Server in Linux

This article provides a tutorial on using SSH to connect to a remote server in Linux. It covers topics such as the basics of SSH, generating and usin… read more

Scheduling Bash Scripts in Linux: Cron, Crontab & More

Learn how to schedule bash scripts to run at specific times in Linux. This article covers topics such as understanding cron and crontab, using the 'a… read more

Comparing Array Sizes in Bash Scripting on Linux

Learn how to compare array sizes in bash scripting on Linux with a variety of code snippets and commands. Discover different approaches such as using… read more

Creating a Bash Script for a MySQL Database Backup

Detailing the process of creating a bash script for MySQL database backup in a Linux environment. Learn how to schedule, automate, and secure your ba… read more

Object-Oriented Bash Scripting in Linux: Quick Intro

Learn about object-oriented programming in Linux with a focus on bash scripting. This article explores the principles of object-oriented programming,… read more

Troubleshooting: Unable to Save Bash Scripts in Vi on Linux

Addressing the issue of saving bash scripts in Vi editor on Linux systems. Troubleshooting common issues with saving bash scripts in vi and understan… read more

How To Echo a Newline In Bash

Learn how to use the echo command in Bash to print a newline character in Linux. The article covers various methods, including using the echo command… read more