[Linux study notes 30] shell script variables

1. Variable


1.1 Definition of variables


Variable is the address of an area of ​​memory


1.2 Types of variables


  1. Local variables Local variables are defined in scripts or commands and are only valid in the current shell instance. Programs started by other shells cannot access local variables.

  2. Environment Variables All programs, including those started by the shell, can access environment variables. Some programs need environment variables to ensure their normal operation. Shell scripts can also define environment variables when necessary.

  3. Shell variables Shell variables are special variables set by the shell program. Some of the shell variables are environment variables, and some are local variables. These variables ensure the normal operation of the shell


2. How to define variables in shell scripts


The export command is used to output shell variables as environment variables or shell functions as environment variables.

When a variable is created, it is not automatically known to shell processes created after it. The export command can pass the value of the variable to the subsequent shell. When a shell script is called and executed, it will not automatically get access to the variables defined in the script (the caller) unless these variables have been explicitly set to be available. The export command can be used to pass the value of one or more variables to any subsequent script.


-f
Represents the function name in [variable name]
-n
Delete the specified variable
(variable is not actually deleted, but not output to
the execution environment of the subsequent instructions)
-p
List all the environment variables assigned to the program by the shell

Insert picture description here

2.1 Environmental level


export 变量=X : Pass variable value

(The variable becomes invalid after the environment is closed )

Insert picture description here
Insert picture description here

2.2 User level


  1. vim ~/.bash_profile
  2. Write export 变量=X
  3. source ~/.bash_profile

Insert picture description here
Insert picture description here

2.3 System level


System level method 1:

  1. vim /etc/profile(It is not recommended to write in the main configuration file)
  2. Write export 变量=X
  3. source /etc/profile

Insert picture description here
Insert picture description here

System level method 2:

  1. vim /etc/profile.d/XXX.sh: In the custom script under the sub-configuration directory
  2. Write export 变量=X
  3. source /etc/profile.d/XXX.sh

Insert picture description here

2.4 Variable name


Suggestion: use capital letters for short names; use "_" for long names

  • Only use English letters, numbers and underscores for naming
  • The first character cannot start with a number
  • No spaces
  • Cannot use punctuation
  • Cannot use keywords in bash (use the help command to view reserved keywords)

3. Escaping of variables


\
Escape a single character
" "
Weak quotation, translate several characters in batch (cannot translate \ `$ !)
' '
Strong citation

Insert picture description here

4. Variable declaration


The curly braces { }are to help the interpreter recognize the boundaries of variables

a=1
echo $ab
echo ${a}b

Insert picture description here



5. Array of Variables


数组名=(值1 值2 ... 值n)
${数组名[下标]}	#读取数组格式

Example 1:

a=(1 2 3 4 5)
${a[0]}	数组第一个元素
${a[-1]}	数组最后一个元素
${a[*]}	所有元素
${a[@]}	所有元素
${a[*]:1:4}	第2-5个元素
${a[@]:1:4}	第2-5个元素
${#a[@]}	元素个数
${#a[*]}	元素个数

Insert picture description here

Example 2:

IP=(`ifconfig ens3 | grep -E "inet\>"`)
echo ${IP}	第一个元素
echo ${IP[1]}	第二个元素
echo ${IP[@]}	所有元素
echo ${#IP[@]}	元素个数

Insert picture description here



6. Command alias setting


1. Temporary settings

alias XXX=‘vim’

Insert picture description here


2. Only valid for the current user

  1. vim ~/.bashrc
  2. Writealias XXX=‘vim’
  3. source ~/.bashrc

3. Take effect for all users of the system

  1. vim /etc/bashrc
  2. Writealias XXX=‘vim’
  3. source /etc/bashrc

4. Delete the alias in the current environment

unalias XXX



7. User environment variables


Environment variable: the command search path used by the user in the operating system


Setting method 1: Current user

  1. vim ~/.bash_profile
  2. Writeexport PATH=$PATH:目录
  3. source ~/.bash_profile

Setting method 2: All users of the system

  1. vim /etc/bash_profile
  2. export PATH=$PATH:目录
  3. source /etc/bash_profile

Insert picture description here
Insert picture description here
Insert picture description here



8. Use command execution results to set variables


8.1 Direct use of command execution results


Priority execution:

  • $(命令)
  • `命令`( ` Backquote)
示例:
TEST=`hostname`	
TEST=$(hostname)

8.2 Passing parameters in scripts


Non-interactive mode

$0
The script itself
$1
The first string of characters after script input
$2
The second string of characters after script input
$3
The third string of characters after script input
$#
The number of input strings after the script
$*
All characters entered by the script (a whole)
$@
All characters entered by the script (multiple wholes)
$$
ID number of the current process running the script
$!
ID number of the last process running in the background
$?
Display the exit status of the last command. 0 means no error, any other value means there is an error

Insert picture description here

Interactive mode

read WESTOS	对WESTOS赋值
read -p "XXXX"	输出提示语
-s	隐藏输出内容

Insert picture description here



9. Script functions


Definition: the alias of the program


Setting method:

函数名()
{
    
    
	action1;
	action2;
}

Function call: function name

In Shell, you can pass parameters to a function when calling it. Inside the function body, the value of the parameter is obtained in the form of $n, for example, $1 means the first parameter, $2 means the second parameter... ${10} means the 10th parameter


test:

create_user.sh determines whether the user exists

  1. Output exists if it exists
  2. If it does not exist, it will be created automatically, and a password will be set up. Finally, the user is displayed
  3. Exit the program when you enter exit

#!/bin/bash
Main()
{
    
    
	read -p "Please input username: " userName
	[ -z "$userName" ] && {
    
    
		Main
		}
	[ "$userName" = "exit" ] || [ "$userName" = "EXIT" ] && {
    
    
		echo "bye !"
		exit
		} || {
    
    
			User_Create $userName
			}
}

User_Create()
{
    
    
	userName=$1	
	id $userName &> /dev/null && {
    
    
		echo "$userName is exist !"
		Main
		} || {
    
    
			read -p "Please input $userName password: " -s Passwd
			echo ""
			useradd $userName
			echo $Passwd | passwd --stdin $userName &> /dev/null
			echo $userName is created successfully !
			Main
			}
}

Main

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_46069582/article/details/111566786