Linux: the use of Linux operating system Shell variables

Use of Shell Variables in Linux Operating System

This blog will introduce how to use Shell variables in the Linux operating system, including variable substitution, definition and operation. By learning these contents, you will be able to better understand and apply Shell variables, and improve the efficiency of scripting and system management.

Shell variable substitution

Shell variable substitution refers to replacing the corresponding variable name with the value of the variable in the command. In a shell script, the form of ${变量名}or can be used $变量名for substitution.

Here is an example:

name="John"
echo "Hello, ${name}!"  # 输出:Hello, John!

define variable

In Shell, we can use =numbers to define variables and assign values ​​to them. Do not have spaces between variable names and values.

Here is an example:

name="John"  # 定义一个名为name的变量,赋值为John
age=25      # 定义一个名为age的变量,赋值为25

echo "My name is ${name} and I am ${age} years old."  # 输出:My name is John and I am 25 years old.

Shell variable operation

Integer operations

The form that can be used for integer operations in the shell $((运算式)).

The following are some commonly used integer arithmetic operators:

  • +:addition.
  • -: Subtraction.
  • *:multiplication.
  • /:division.
  • %: Take the modulo (remainder).

Here is an example:

num1=10
num2=5

sum=$((num1 + num2))
echo "Sum: $sum"  # 输出:Sum: 15

product=$((num1 * num2))
echo "Product: $product"  # 输出:Product: 50

remainder=$((num1 % num2))
echo "Remainder: $remainder"  # 输出:Remainder: 0

Decimal operations

To perform decimal operations in the Shell, you can use bccommands to achieve. bcis a high-precision calculator for mathematical calculations.

Here is an example:

num1=10.5
num2=3.2

sum=$(echo "$num1 + $num2" | bc)
echo "Sum: $sum"  # 输出:Sum: 13.7

product=$(echo "$num1 * $num2" | bc)
echo "Product: $product"  # 输出:Product: 33.6

script example

Here is an example script that demonstrates the use and manipulation of shell variables:

#!/bin/bash

# 定义变量
name="John"
age=25

# 输出变量值
echo "My name is ${name} and I am ${age} years old."

# 整数运算
num1=10
num2=5

sum=$((num1 + num2))
echo "Sum: $sum"

# 小数运算
num3=10.5
num4=3.2

product=$(echo "$num3 * $num4" | bc)
echo "Product: $product"

Save the above content as a variable_script.shscript file named , and grant execution permission ( chmod +x variable_script.sh). Then run the script ( ) in the terminal ./variable_script.shto see the output.

in conclusion

This blog introduces the usage of Shell variables in the Linux operating system, including variable substitution, definition and operation. By learning and applying this knowledge, you can become better at writing shell scripts and system administration. Hope this blog was helpful to you!

Guess you like

Origin blog.csdn.net/run65536/article/details/131414697