Skip to content

Summary of different types of variables in Bash

homepage-banner

Introduction

Bash is a widely used shell for Unix-based operating systems. It is a powerful tool for automating tasks and running scripts. In Bash, variables are used to store values and data that can be used throughout a script. There are different types of variables in Bash, each with its specific purpose and function. In this blog post, we will discuss some of the most commonly used types of variables in Bash.

1. Local Variables

VAR=XYZ

2. Local Variables

local VAR=XYZ

3. Environment Variables

Works in subshells.

export VAR=XYZ

4. Positional Variables

$0  Script name itself
$1  First argument
$2  Second argument
...
${10}  Tenth argument
${11}  Eleventh argument
shift  Shift arguments to the right

For example, display the first, second, and third arguments respectively.

!#/bin/bash
echo $1
shift
echo $1
shift
echo $1

5. Special Variables

$?    # Script execution status (0--correct, 1-255 error, 1/2/127 reserved)
$#    # Total number of arguments
$*    # List of arguments
$@    # List of arguments

Conclusion

In this blog post, we discussed some of the most commonly used types of variables in Bash. Environment variables are system-level variables that are set outside of a script and can be accessed by any program or process running on the system. Local variables are defined within a script and are only accessible within that script. Command-line arguments are values that are passed to a script or program when it is run. By understanding the different types of variables in Bash, you can write more efficient and effective scripts.

Leave a message







Disclaimer
  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback me#imzye.com, replace # with @