Bash 변수

Variables are an essential concept in bash scripting. They allow you to store and manipulate data, making your scripts more dynamic and flexible. In this blog post, we will explore the basics of bash variables, how to declare and use them effectively in Linux.

What is a Variable in Bash?

A variable in bash is a named entity that stores a value. It can hold various types of data, such as numbers, strings, arrays, or even command outputs. Variables are used to store temporary or persistent data that is used within a script or by other processes.

Declaring Variables

To declare a variable in bash, you can use the following syntax:

variable_name=value

It’s important to note that there should be no spaces around the equal sign (=) when assigning a value to a variable.

Variable Naming Rules

When naming variables in bash, you need to follow a set of rules:

Variable Types

Bash variables are by default treated as strings. However, you can assign different types of values to them. Here are the most common types:

String Variables

To assign a string value to a variable, enclose the value in single or double quotes:

name='John'

Integer Variables

To declare an integer variable, you don’t need any special syntax. Just assign the value without quotes:

age=25

Array Variables

In bash, you can create an array variable to store multiple values. To declare an array, use the following syntax:

fruits=('apple' 'banana' 'orange')

Accessing array elements is done using the index:

${fruits[1]} # Accesses the second element 'banana'

Using Variables

To access the value stored in a variable, you need to prefix the variable name with a dollar sign ($). For example:

echo $name # Prints the value of name variable ('John')

You can also perform operations and manipulate variables:

result=$((age + 5)) # Adds 5 to the age variable and stores the result in result variable

Environment Variables

Bash also has environmental variables that are predefined and available to all running processes. They provide information about the system environment, such as the user executing the script, the current working directory, and system-specific information.

Some common environmental variables include:

Conclusion

Bash variables are powerful tools that enable you to store and manipulate data within your scripts. Understanding their syntax, types, and usage will greatly enhance your ability to write efficient and dynamic bash scripts. So start using variables in your Linux projects and unlock the full potential of your scripts.