Shell Programming and Variables

Posted by khujo56 on Fri, 21 Jan 2022 12:08:54 +0100

1. Overview

1. Concepts

1) What is a shell:

shell Is a command interpreter, which is responsible for directly talking with the user at the outermost level of the operating system, interpreting the user's input to the operating system, processing the output of a wide variety of operating systems, and outputting to the screen for feedback to the user. This conversation can be interactive or non-interactive,The command we entered is not recognized by the computer, so we need a program to help us translate it into a binary program that the computer can recognize, and at the same time return the results generated by the computer to us.
  • Save the commands to be executed in order to a text file
  • Give this file executable permissions
  • Combining various shell control statements to complete more complex operations

2) What is a shell script:

A shell 1 script means that when we put the original linux command or statement in a file and execute it through this program file, we call it a shell script or shell.

Procedure; We can enter a system of commands and related syntax combinations, such as variables, into the script.
Process control statements, etc., combine them to form a powerful shell script

Summary: The commands that need to be executed are saved in a file and executed sequentially. It does not need to be compiled. It is interpreted

3) What a shell script can do

  • Automatically complete installation and deployment of software, such as installing and deploying LAMP Architecture Services
  • Automatically complete system management, such as adding users in bulk
  • Automatically complete backups, such as database backups
  • Automated analysis and processing, such as site visits

4) She1 script usage scenarios

When a lot of complex and repetitive work needs to be done, instead of repeating commands on the command line, running shell scripts directly saves time and improves efficiency

2.shell Role - Command Interpreter, "Translator"

A shell on a Linux system is a special application between the operating system kernel and the user
The shell in Linux system is a special application, which is between the operating system kernel and the user, and acts as a "command interpreter", which receives and interprets the operation instructions (commands) input by the user, passes the operations that need to be performed to the kernel for execution, and outputs the results of execution.

Interpreter: System software capable of executing programs written in other computer languages

There are many common shell interpreter programs. When using different shells, there are some differences in their internal instructions, command line prompts, and so on. The / etc/shells file lets you know the kinds of shell scripts supported by the current system.

[root@localhost ~]# cat /etc/shells
/bin/sh#It is a soft link to the bash command (replaced by / bin/bash)/bin/bash based on a shell developed within the framework of the GNU.
/usr/bin/sh Already Covered bash Replaced.
/usr/bin/bash #centos and redhat systems use bash shell by default
/bin/tcsh #Enhanced version of csh, fully compatible with csh, integrates CSH to provide more functionality. / bin/csh has been replaced by / bin/bash (integrated c shell for more functionality)

notes: nologin:Strange shell,this shell Can prevent users from logging on to the host.
bash ( /bin/bash)Currently most Linux Default for version shell. 
1)Why is it legal on our system shell To write/etc/shells This file?
This is because some of the services in the system are running to check what users can use shells,And these shell Queries are just excuses/etc/ shells This file.

2)When can users get it shell To work?And which one do I get by default? shell?
When I log on, the system will give me shell Let me work, and this login gets it shell On record/etc/passwd Inside this file.
Different shell They have different functions. shell And decided Linux Default in shell yes/bin/bash,Fashionable shell Yes ash,bash,ksh,csh,zsh Wait, different shell They all have their own characteristics and uses
 At present most linux The system defaults to bash

shell,Default login shell yes/bin/bash,Can View/etc/passwd Note in the file
 this shell For users, you can view/etc/passwd Which of the last fields inside uses shell,If you want to modify it, you can use chmod -s perhaps chsh -s To reassign

3. Script Composition

First Act"#!/ Bin/bash ", script declaration (default interpreter):Indicates that the code statements below this line are executed through the / bin/bash program. There are other types of interpreters,

such as#! /usr/bin/python,#!/usr/bin/expect

annotation:with"#"The beginning statement is a comment message, and the commented statement is not executed when the script runs: for example, the echo command to output a string between""

Example:
vim first.shcd /boot/pwd
ls -lh vml*

Example:
#!/bin/bash
#This is my first shell-script.cd /boot
echo "The current directory is located in:"pwd
echo "Where vml Beginning files include:"ls -lh vml*

4.shell Programming Specification

1. Creation steps:

1.Create a file containing command and control structures
2.Modify the permissions of this file so that it can be executed, chmod +x xxxx.sh
3.Detect grammar errors
4.implement  ./xxxx.sh

2. How to execute the script:

Method One:
Execute script under current path (absolute path vs. relative path) (with execute privileges))
/home/first.sh perhaps./first.sh

Method 2:
sh . bash Strength of script files (this way you don't add execute permissions to script files))
bash first.sh or sh first.sh

Method Three: 
source Script File Strength(Can not have execute permission)source first.sh

Method 4:Other methods
sh < first.sh perhaps cat first.sh |sh (bash)

5. Redirection and piping

1) Interactive hardware devices

  • Standard Input: Receive user input data from the device
  • Standard Output: Output data to the user through the device
  • Standard error: Error information is reported by the device
type          Device Files     File Description Number    Default device
 Standard Input      /dev/stdin    0             keyboard
 standard output      /dev/stdout   1             Monitor
 Standard error output  /dev/stderr   2             Monitor
Redirect operation:
type	      Operator	 purpose
 redirect input	 <	     Read data from specified file
 redirect output	 >	     Saves the standard output results to the specified file, overwriting the original contents
 redirect output	 >>	     Appends the standard output to the end of the specified file without overwriting the original contents
 Standard error output	2>	    Saves the error information to the specified file and overwrites the original content
 Standard error output	2>>	    Appends the error information to the end of the specified file without overwriting the original contents
 Mixed Output	 &>	     Save standard output, standard errors to the same file
 Mixed Output	 2>&1	 Redirect standard error output to standard output

2) Redirect output

Redirected output refers to saving the normal output of a command to a specified file, rather than displaying it directly on the display screen.
Redirected output uses the'>'or'>'action symbol to overwrite or append files, respectively
If the target file for the redirected output does not exist, it will be created, and the output from the previous command will be saved to the file; if the target file already exists, the output will be overwritten or appended to the file.

>:Means that if there is content in the original file, it will be overwritten

>>:This means that if there is something in the original file, the new content will be appended to it without overwriting the original content.
For example:
uname -p > kernel.txt

[root@localhost ~]# cat l.txt//keyboard as input device, which is also the default system 1234

[root@localhost ~]# cat <1.txt
1234
//Follow cat 1. The txt result is the same, but this is 1.txt file as input device

By default, cat The command accepts input from a standard input device (keyboard) and displays it to the console, but if a file is used instead of a keyboard as the input device, the command takes the specified file as the input device and reads and displays the contents of the file to the console.

[root@localhost ~] # cat <<0
//With o as the delimiter, as long as you don't enter o, you enter data all the way to the screen
>123
>456
>0
123
456
[root@localhost ~]# cat << 0 > a.txt
//You can use input redirection with output redirection to save the output from the screen to a file >123
>456
>0
[root@localhost ~]# cat a.txt
123
456


cat << o gtyguyuhuih 0

Example 1:Separate error display from correct display
ls /etc/passwd  XXXX
ls:cannot access xxx:No file or directory
/etc/passwd

ls letc/passwd xxx > a.txtl
ls:cannot access xxx:No file or directory
cat a.txt
/etc/passwd

ls /etc/passwd xxx 2> a.txt
/etc/passwd
cat a.txt
ls:cannot access xxx:No file or directory
 notes:Use 2>When using an operator, it looks like using>Overwrite the contents of the target file as well. If you append without overwriting the contents of the file, you can use 2>>Operator

Column:
tar jcf /nonedir/etc.tgz /etc/ 2> error.log
cat /error.log

example:
In automated scripts that compile source packages, to ignore make,make install Operational process information, such as, can be directed to an empty file/dev/null. 

# !/bin/bash 
#Automatically compile scripts for installing httpd servers
cd /usr/src/httpd-2.4.25/
./configure --prefix=/usr/local/httpd --enable-so &> /dev/nullmake &> /dev/null
make install &> /dev/null 
#/dev/null is equivalent to make install >/dev/null 2>&

Error redirection:
Error redirection refers to saving error information (such as options or parameter errors) that occurs during command execution to a specified file, rather than displaying it directly on the screen. Error redirection using the 2> operator

Two roles:
In practice, error redirection can be used to collect error information for program execution and provide a basis for error correction.
You can also redirect trivial error information to an empty file/dev/null to keep your script output concise

When using the 2> operator, the contents of the target file are overwritten as if using the 2> operator. To append content instead of overwriting the file, use the 2> operator instead.

When the output of a command may include both standard output (normal execution) information and error output information, you can use the operator'>''2>' to save the two types of output information to different files, or the'&>'operator to save the two types of output information to the same file.

3) Pipeline operation

Pipeline ( pipe)Operations provide a mechanism for collaboration between different commands, located in pipe symbols"|"The output of the command on the left will be used as input to the command on the right (processing object)),Multiple pipelines can be used in the same line of commands.
stay shell In scripting applications, pipeline operations are often used to filter critical information needed.
$bash $Represents a system prompt, $Indicates that this user is a normal user, and the prompt for the superuser is#bash is one of the shells and is the most commonly used shell under linux
$bash Means to execute a child shell,This son shell by bash.
example:
rpm -qa | grep httpd
grep "/bin/bash$" /etc/passwd | awk -F: '{print $1,$7 }'
column:
df -hT | grep "/$" | awk '{print $6}'I
 summary:
Redirection and piping operations are shell Functions that are commonly used in the environment can help you write simple but powerful code if you are skilled and flexible shell Script program

Two, shell variables

Role, type of Shell variable

The role of variables
●Used to store specific parameters (values) that the system and user need to use)
Variable Name:Use a fixed name, defined by system preset or user
 Variable Value:Ability to change according to user settings, system environment changes

Type of variable
●Custom variable:User-defined, modified, and used
●Special variables:Environment variables, read-only variables, location variables, predefined variables

1. Custom variables

Definition of variables:

Variable operations in Bash are relatively simple and less complex than other advanced programming languages such as c/c++, Java, and so on. When defining a new variable, you generally do not need to declare it in advance, but rather specify the name of the variable and assign it to the initial value (content).

format:Variable Name=Variable Value
 Variable Name:A place to temporarily store data
 Variable Value:Temporary Variable Data

Permanent environment variables exist~/.bashrc Files (not disappear after power loss or restart), in each shell On startup, permanent environment variables are imported into shell And become shell A temporary environment variable that can be used to unset After drop, but will not affect other shell, Because we're going to say, different shell Temporary environment variables are independent of each other.

There are no spaces on either side of the equal sign. Variable names should begin with a letter or an underscore and should not contain special characters (such as+,-,*,/, ., ?,%,&,#Etc.)
use echo Viewing and referencing the value of a variable
 By prefixing variable names with leading symbols"$",You can reference the value of a variable using echo The command can view variables, and it can be used in one echo View multiple variable values simultaneously in a command
 Example:
Product=Python
version=2.7.13
echo $Product$version
 When variable names are easily confused with other characters that follow them, braces need to be added"{}"Enclose it or you will not be able to determine the correct variable name. For undefined variables, null values are displayed
 Example:
echo ${Product}2.5
echo ${test}RMB
echo option
echo -n Represents non-newline output
 Use echo -e Output escape characters, output the escape to the screen

Common escape characters are as follows:
\c:No line break output, in"\c"In the absence of a character after it, the effect is equivalent to echo -n
\Line Break
\t:Escaped to indicate insertion tab,Tab
 notes:\Escape character, following\Special symbols will lose their special meaning and become ordinary characters.
as\s Will output"s"Symbol, not as a variable reference
 example:
[root@localhost ~]#echo -n hello
hello [root@localhost ~]#

Undefine
unset Variable Name

Special operations
 There are also special assignment operations that allow you to assign variables more flexibly for complex administrative tasks
 Double Quotes("")
Double quotation marks are used primarily to define strings, especially when space is included in the assignment;In other cases double quotation marks can usually be omitted
1,When there are spaces in the content
echo "hello world"
echo nihao
2,When assigning values to variables
[root@localhost ~]# version=2
[root@localhost ~]# pyver="python $version"
[root@localhost ~]# echo $pyver
python 2

Single quotation mark('')
When the content to be assigned contains $,",\Single quotation marks should be used when such characters have special meaning.
Within single quotation marks, values of other variables cannot be referenced, and any characters are treated as normal characters. The assignment contains single quotation marks (single quotation marks)')When using\'Symbols are escaped to avoid conflicts.
[root@localhost ~]# test=123
[root@localhost ~]# echo "$test"
123
[root@localhost ~]# echo '$test'
$test

Apostrophe(``)
The undo sign is primarily used for command substitution, allowing you to assign the screen output of a command to a variable. The scope enclosed in apostrophes must be a command line that can be executed or an error will occur
ls -lh 'which useradd`
Pass First which useradd Command Find useradd Command's program location, and then list file properties based on the results of the lookup
date +Number Y-%m-%d
[root@localhost ~]# time=`date +%T`
[root@localhost ~]# echo $time
04:23:22

It is difficult to replace nested commands in a single line of commands with an apostrophe, and you can use it instead"$()"To replace the apostrophe to solve nesting problems
rpm -qc $(rpm -qf $(which useradd))

2. Input assigns values to variables

Interactively defining variables

read command
Use Bash's built-in command read to assign values to variables.
Used to prompt the user to enter information for simple interaction. When executed, a line is read from the standard input device (keyboard), and each field read is assigned to the specified variable in turn with a space separator (the extra content is assigned to the last variable). If only one variable is specified, the entire line is assigned to the variable.

[root@localhost ~]# read test
123        /Wait for user input, assign input value to test variable
[root@localhost ~]# echo $test
123

In general, to make the interactive interface more user-friendly and easier to use, the read command can be combined with the'-p'option to set prompts to inform the user what to enter, and so on.

[root@localhost ~]# Read-p "Please enter your name:" name
 Please enter your name:zhangsan
[root@localhost ~]# echo $name
zhangsan

Interactively define variables (read)
-p Prompts the user for information
-n defines the number of characters
-t Defines the time-out, how long to quit without losing
-s does not display user input and is often used to enter the password read-s-p "input your password:" pass

Read from a file and assign to a variable
[root@server myscripts]# echo 192.168.100.100 > ip.txt
[root@server myscripts]# cat ip.txt
192.168.100.100
[root@server myscripts]# read -p "input your ip:" IP < ip.txt
[root@server myscripts]# echo $IP
192.168.100.100

Scope of the variable

Global and local variables

By default, newly defined variables are only valid in the current shell environment and are therefore called local variables when entering a subroutine or a new subroutine
Local variables are no longer available in shell environments

[root@localhost ~]# bash#Enter child shell environment
[root@localhost ~]# echo $name
[root@localhost ~]# echo $test

export command:
To enable user-defined variables to continue to be used in all child shell environments and to reduce duplicate settings, you can export the specified variables as global variables through the internal command export.
Users can specify multiple variable names as parameters at the same time (without using the "s" symbol), with variable names separated by spaces

[root@localhost ~]# exit
exit
[root@localhost ~]# export name test
[root@localhost ~]# bash
[root@localhost ~]# echo $name $testexit
zhangsan 123
 or
[root@localhost ~]# echo "$Product $version"
Benet 6.o
[root@localhost ~]# export Productversion #Export as Global Variable[root@localhost ~]# bash
[root@localhost ~]# echo "$Product $version"#The subroutine references the global variable Benet6.0
[root@localhost ~]# exit

Export can also be used to export global variables, so that when a global variable is newly defined, env doesn't have to be assigned in advance to view the user's current environment variables
export ABC=123
env can see it again
Expo-n ABC Undefined Global Variable to Local Variable

3. Operation of numerical variables

In the Bash shell environment, only simple integer operations can be performed. Decimal operations of integer values are not supported. Operators and variables must have at least one space between them mainly through the internal command expr.

Operation content: add (+), subtract (one), multiply (*), divide (/), take (%)
Operational Symbols: ( ( ) ) and ()) and (()) and []
Operational commands: expr and let
Operating tool: BC (system-built)

The common Guilli operators used by the expr command (which not only performs operations but also supports output to the screen) are described below.

  • +: Addition operation.
  • -: subtraction operation.
  • : In multiplication, note that you cannot use only the'*'symbol, otherwise it will be used as a file wildcard.
  • /: Division operation.
  • %: A modulus operation, also known as a complement operation, is used to calculate the remainder after dividing a number.
Example:
[root@localhost~]# expr 1 + 1
2
[root@localhost~]# expr 1+1
1+1
[root@localhost~]# expr 2 * 2
expr:Syntax error
[root@localhost~]# expr 2 \* 2  ##Multiplication* needs escaping
4
[root@localhost~]# expr 2 '*' 2   ##Multiplication can also be expressed in single quotes, but not necessarily because there is only one character
4

expr supports not only constants but also variables:

Example 1

[root@localhost ~]# X=35
[root@localhost ~]# Y=16
[root@localhost ~]# expr $X + 5
40
[root@localhost ~]# expr $X + $Y
51
[rootelocalhost ~]# expr $X - $Y
19
[root@localhost ~]# expr $X \* $Y
560
[root@localhost ~]# expr $X / $Y
2
[rootelocalhost ~]# expr $X % $Y
3

Example 2

sum=`expr $Y \*$Y \* $Y`
echo $sum

Example 3

#!/bin/ bash
#1. Define the output number Ning
read -p "Please enter the first number:" num1
read -p "Please enter a second number:" num2

#2. Perform addition operations
expr $num1 + $num2
echo "Summation:$sumn"

[ ] and [] and [] and (()) must be used with echo because he can only operate and cannot output results

[root@localhost~]# echo $((1+1))
2
[root@localhost~]# echo $((5-2))
3
[root@localhost~]# echo $((a-b))
7
[root@localhost~]# echo $((b-a))  ##Can have negative numbers
-7

$[] integer operation

[root@localhost~]# echo $[10*10]      ##* in $[] does not need escaping
100
[root@localhost~]# echo $[10%8]
2
[root@localhost~]# echo $[10/8]
1
[root@localhost~]# echo $[10/12]
0
[root@localhost~]# echo $[10%12]
10

[ ] change amount Of transport count , can province slightly [ ] in Of The operation of variables can be omitted The operation of variables can be omitted

[root@client opt]# echo $[$a+$b]
13
[root@client opt]# echo $[a+b]
13
[root@client opt]# echo $[a-b]
7
[root@client opt]# echo $[a*b]
30
[root@client opt]# echo $[a/b]
3

4.let and bc operations

i++  ----  i=$[$i+1]
i--  ----  i=$[$i-1] 
i+=2 ----  i=$[$i+2]

let's operation can change the value of the variable itself, but does not show the result. echo is required. Other operations can do the operation without changing the value of the variable itself

[root@localhost~]# n=1;let n=n+1;echo $n
2
[root@localhost~]# let n+=2   #Equivalent to n=n+2
[root@localhost~]# echo $n
4
[root@localhost~]# let n=n**2  #Exponentiation, 2nd power of 4
[root@localhost~]# echo $n
16
[root@localhost~]# let n++    #n self-adding 1
[root@localhost~]# let n--l   #n minus 1
[root@localhost~]# echo $n
16
[root@localhost~]# echo $[n++]    #First output and then increase by 1, the value of a has changed to
16
[root@localhost~]# echo $n        #Output the value above
17
[root@localhost~]# echo $[++n]      #It increases by 1 and then outputs, so it directly outputs the changed value
18
[root@localhost~]# echo $n
18

bc is used for operations, supporting decimal operations, but cannot be used directly in scripts or it will enter an interactive interface, which can be used in combination with echo pipeline

[root@localhost ~]# bc
bc 1.06.95
copyright 1991-1994,1997,1998,2000,2004,2006 Free Software Foundation,Inc.This is free software with ABSOLUTELY NO WARRANTY.
For details type 'warranty'.
10/ 3
3
scale=3     #Specify the digits after the decimal point
10/3
3.333
[root@localhost ~]# echo "scale=3;10/3" | bc
3.333
[root@localhost ~]# echo "3^2" | bc   #Do a power operation and calculate the square of three
9

bc operates on variables:

[root@localhost ~]# a=10
[root@localhost ~]# b=3
[rootelocalhost ~]# echo "$a/$b" | bc
3
[root@localhost ~]# echo "scale=2; $a/$b" | bc
3.33
 You can try to calculate the area of a circle

bc can also do logical operations, true 1, false 0

[root@localhost ~]# echo "2>2"| bc
0
[root@localhost ~]# echo "2==2" | bc
1
[root@localhost ~]# echo "2<2"| bc
0
Common Operational Expressions:
i=$ (expr 12 \* 5)
i=$((12 * 5))
i=[12 * 5]
let i=12*5

i++   Amount to i=$[$i+1]
i--   Amount to i=$[$i-1]
i+=2  Amount to i=$[$i+2]

5. Special variables

1) Environment variables

Environment variables refer to a kind of variables created in advance by the Linux system for the purpose of running. They are mainly used to set the user's working environment, including user host directory, command lookup path, user's current directory, login terminal, etc.

The value of the environment variable is automatically maintained by the Linux system and changes as the user's state changes.
The env command allows you to see the environment variables in your current working environment, and for some common environment variables, you should understand their respective uses.

For example,
The variable USER denotes the user name,
HOME represents the user's host directory,
LANG represents the language and character set.
PWD represents the current working directory.
PATH means command search path, etc.
RANDOM represents a random number and returns an integer of 0-32767.
USER denotes the account name of the current account, etc.

Usually defined in full capitals, note the distinction between and custom variables

[root@localhost ~]# echo $RANDOM
20315
[roote1ocalhost ~]# echo $HOME
/root
[root@localhost ~]# echo $USER
root
[rootelocalhost ~]# echo $LANG
zh_cN.UTF-8
[rootelocalhost ~]# echo $SHELL
/bin/bash
[root@localhost -]# In echo $RANDOM linux, $random is used to generate random number 18945 of 0-32767
18945

PATH path environment variable:
The PATH variable is used to set the default search path for executable programs. When only the file name is specified to execute the command program, the system will look for the corresponding executable in the directory range specified by the PATH variable and prompt "command not found" if it is not found.

[root@localhost ~]# test.sh
bash: test.sh:Command not found...
[root@localhost ~]# echo $PATH
/usr/local/sbin:/usr/locai/bin:/usr/sbin:/usr/bin:/root/bin
[root@localhost ~]# pwd
/root

Because of test.sh is not in the $PATH directory, so the system cannot recognize that it cannot be used directly and needs to keep up with absolute paths to use the script

Method 1:

Add Directory of Scripts $PATH
[root@localhost ~]# PATH="$PATH:/root"
//This is temporary.
Edit required if permanent effect/etc/profile file
[root@localhost ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root
[root@localhost ~]# test.sh
hello world

Method 2:

Put your own script on P A T H in Of some one individual order record stay L i n u x system System in , ring Territory change amount Of whole game match Location writing piece by / e t c / p r o f i l e , stay this writing piece in set righteousness Of change amount do use to place Yes use household . except this of abroad , each individual use household still Yes since You Of single Stand match Location writing piece (   / . b a s h p r o f i l e ) . repair change finish Yes want heavy new Den land just can living effect , as fruit think Stand That is living effect , can with send use s o u r c e notes meaning : repair change A directory in PATH On Linux systems, the global configuration file for environment variables is/etc/profile, in which the variables defined act on all users. In addition, each user has his or her own separate profile (~/.bash_profile). Modifications need to be re-logged in before they take effect. If you want them to take effect immediately, you can use source Note: Modifications A directory in PATH On Linux systems, the global configuration file for environment variables is/etc/profile, in which the variables defined act on all users. In addition, each user has his or her own separate profile (/.bashp rofile). Modified to re-login in order to take effect, if you want to take effect immediately, you can use source Note: Modifying PATH requires careful action, if you can not find it will affect the use of commands!!!

for example:
[root@localhost ~]# PATH=        #Wrong setting of PATH to empty
[root@localhost ~]# echo $PATH
[root@localhost ~]# ls
-bash: ls:No file or directory

2) Read-only variables

There is a special case in shell variables where once set, the value is immutable and is called a read-only variable.
You can set a variable as a read-only property when you create it, or you can set an existing variable as a read-only property.
Read-only variables are mainly used when variable values are not allowed to be modified. Read-only variables cannot be changed or deleted

[root@localhost ~]# test=123
[root@localhost ~]# readonly test
#Readonly is used to define read-only variables that cannot be changed in a script once they are defined with readonly
[root@localhost ~]# echo $test
123
[root@localhost ~]# test=456
-bash: test:read-only variable
[root@localhost ~]# unset test
-bash: unset: test:Unable to reverse settings:read-only variable
 Temporarily set, just exit login to resume

3) Location variable

When performing a command line operation, the first field represents the command name or script program name, and the remaining string parameters are assigned to the location variables in order from left to right.
Location variables, also known as position parameters, are represented by $1, $2, $3,..., $9
The name of the command or script itself is denoted by'$0'

Example: Write a simple script to create a user and password
[root@localhost ~]# vim user.sh
#!/bin/bash
useradd $1
echo $2 | passwd --stdin $1
##Exit vim editor to execute script
[root@localhost ~]# bash user.sh sj 123
 Change User sj Password.
passwd:All authentication tokens have been successfully updated.
[root@localhost ~]# id sj
uid=1001(sj)gid=1001(sj)group=1001 (sj)

Example:
[rootelocalhost ~]# vim adder2num.sh
#!/bin/bash
SUM=`expr $1 + $2`
echo "$1 + $2 = $SUM"

[root@localhost ~]# chmod +x adder2num.sh
[root@localhost ~]# ./adder2num.sh 12 34 
#$1 for 12 $2 for 34 12 + 34 = 46
[root@localhost ~]# ./adder2num.sh 56 78 
#$1 for 56 $2 for 78 56 + 78 = 134


4) Predefined variables

Predefined variables are special variables that are predefined by the Bash program. Users can only use predefined variables, not create new predefined variables, nor assign values directly to them. Predefined variables are represented by a combination of the'$'symbol and another symbol

  • $#: Indicates the number of positional parameters on the command line.
  • $*: Represents the contents of all location parameters as a whole
  • $@: Indicates that all location parameters are listed, but in a single form
  • $?: Represents the return status of the previous command after execution, with a return value of 0 indicating correct execution, and returning any non-zero value indicating an exception to execution.
  • $0: Represents the name of the script or program currently executing
  • $$: Process number indicating the return of the current process
  • $!: Return the process number of the last background process

Example: Understand the meaning of each predefined and location variable based on a simple script

#!/bin/bash
echo $1
echo "$0 Represents the name of the script or program currently executing"
echo "$# Represents the number of positional parameters on the command line.
echo "$* The content of all the location parameters as a whole"
echo "$@ Indicates that all location parameters are listed, but in a single form"

Example 2: You can optimize your script

#!/bin/bash
echo "The current script name is $o"
echo "The first parameter of the current script is $1"
echo "The second parameter of the current script is $2"
echo "Current scripts are common $#Parameters "

Example 3 touch/home/ kgc. Txt &

echo "$$  Represents the process number that returns the current process"
echo "$?  0 Correct, 1 Error"
echo "$!  Return the process number of the last background process"

Understand the difference between $* and $@

  • ∗ , *, , @: Indicates the parameters to be processed by a command or script.
  • $*: Returns all parameters as a space-delimited string (single string) representing'$1 $2 $3 $4'.
  • $@: Separates each parameter with double quotes into n parameter lists, and returns each parameter as a string representing'$1','$2','$3','$4'.

Add the following two lines to the script and execute

touch "$*"
touch "$@"

Ls-l See which files were created

Summary:
$* treats all parameters as a whole
$@is to treat each parameter as a separate individual

Set: View all variables in the system, including environment variables and custom variables (you can set pipeline filtering without a command to view custom variables separately)

Topics: Linux Operation & Maintenance shell bash