Getting Started with Shell Scripting: Writing Format and Execution

content

Shell script file writing specification

Shell Script HelloShell Getting Started Case

There are 3 common ways to execute shell script files

         Getting Started with Shell Scripting: Multiple Command Processing

         Shell Variables: Environment Variables

Introduction to Shell Variables

Shell system environment variables

         Shell Variables: Custom Variables

Introduction to Shell Custom Variables

Shell custom constants

         Shell Variables: Special Variables

        Special variable: $n

        Special variable: $#

        Special variables: $*, $@

        Special variable: $?

        Special variable: $$


Shell script file writing specification

Script file extension specification

The shell script file is a text file, and the suffix name is recommended to .shend with

First line format specification

The first line needs to set the shell parser type, syntax

Meaning: Set the current shell script file to use the bash parser to run the script code

#!/bin/bash

Comment format

  • single line comment, syntax
# 注释内容
  • multi-line comments, syntax
:<<!
# 注释内容1
# 注释内容2
!

Shell Script HelloShell Getting Started Case

  • Create a shell script file helloworld.sh that outputs the hello world string.

1. Create a shell script file

touch helloshell.sh

2. Edit the file

gedit helloshell.sh

3. Add the content of the shell script file as follows, and save and exit

#!/bin/bash
echo "hello shell"

4. Execute the script

sh helloshell.sh

Effect

There are 3 common ways to execute script files

  1. sh parser execution mode

    grammar:sh 脚本文件

    Introduction: is to use the sh command to execute the script file, the essence is to use the shell parser to run the script file

  2. bash parser execution mode

    grammar:bash 脚本文件

    Introduction: is to use the bash command to execute the script file, the essence is to use the shell parser to run the script file

  3. Path execution only

    grammar:./脚本文件

    Description: Execute the script file in the current directory

    Note: The script file needs to have executable permission to execute itself, otherwise it cannot be executed

  • Execute script mode 1-sh command execution
sh helloshell.sh
  • Execute script mode 2-bash command execution
bash helloshell.sh
  • Execute script mode 3 - only path execution

       Add execute permission

chmod a+x helloshell.sh
./helloshell.sh

What are the 3 ways to execute shell script files and explain their differences?

sh execute script file

bash execute script file

Only path to execute script file

Difference: The first two are that the parser does not need executable permissions for direct execution, and the last one is that the script file itself needs executable permissions to execute


Getting Started with Shell Scripting: Multiple Command Processing

Introduction to multi-command processing

Is to write multiple shell commands in a shell script file

  • Knowing the directory /root/itheima, execute the batch.sh script to create a one.txt in the /yj/Shell/ directory, and add the content "Hello Shell" to the one.txt file.

1. Enter the yj directory and execute the command to create the /yj/itheima directory

mkdir /yj/Shell

2. Create the /home/yj/batch.sh file

touch batch.sh

3. Edit the batch.sh file and write shell commands

gedit batch.sh

4. Write the command

Command 1: Create /home/yj/Shell/one.txt file

Command 2: Output "I love Shell" string data to one.txt file

#!/bin/bash
cd Shell    # 切换到Shell目录
touch one.txt  # 创建文件one.txt
echo "I love Shell">>/home/yj/Shell/one.txt  #输出数据到one.txt文件中

run script effect

Run the batch.sh script file

sh batch.sh

View the content of the one.txt file

cat Shell/one.txt


Shell Variables: Environment Variables

Introduction to Shell Variables

Variables are used to store and manage temporary data, which are all in runtime memory.

variable type

  1. system environment variables

  2. custom variable

  3. special symbol variable

system environment variables

introduce

It is a shared variable provided by the system. It is a variable defined in the configuration file loaded by the Linux system to be shared by all Shell programs.

Shell configuration file classification

1. Global configuration file /etc/profile /etc/profile.d/*.sh /etc/bashrc

2. Personal profile current user/.bash_profile current user/.bashrc

In general, we operate directly on the global configuration.

Classification of environment variables

In the Linux system, environment variables can be roughly divided into system-level environment variables and user-level environment variables according to their different scopes.

System-level environment variables: The shell environment loads variables in the global configuration file and is shared with all shell programs of all users. User-level environment variables are globally shared: The shell environment loads the variables in the personal configuration file and is shared with the current user's shell program, and the logged-in user use

View the current shell system environment variables

view command

env

View Shell variables (system environment variables + custom variables + functions)

set

Common system environment variables

variable name meaning
==PATH== Like the Windows environment variable PATH function, set the search path of the command, separated by colons
HOME Current user home directory: /root
SHELL Current shell parser type: /bin/bash
==HISTFILE== Display the history list file of commands executed by the current user: /root/.bash_history
PWD Display the current path: /root
OLDPWD show previous path
HOSTNAME Show current hostname: itheima
HOSTTYPE Display the architecture of the host, whether it is i386, i686, or x86, x64, etc.: x86_64
==LANG== Set the current system locale: zh_CN.UTF-8

Environment variable output demo

4. Common environment variables

variable name meaning
PATH The directory path searched by the command is the same as the Windows environment variable PATH function
LANG Query the character set of the system
HISTFILE Query the history list of commands executed by the current user


Shell Variables: Custom Variables

Introduction to custom variables

is the variable you define

Classification

  1. custom local variable

  2. custom constant

  3. custom global variable

custom local variable

  • introduce

It is a variable defined in a script file, and a variable that can only be used in this script file is a local variable

  • Definition and use

Definition grammar

var_name=value

Variable Definition Rules

  1. Variable names can contain letters, numbers and underscores, but cannot start with a number

  2. No spaces on either side of the equal sign

  3. In the bash environment, the default types of variables are string types, and numerical operations cannot be performed directly

  4. If the value of the variable has spaces, it must be enclosed in double quotes

  5. Cannot use shell keywords as variable names

demo

query variable value syntax

# 语法1: 直接使用变量名查询
$var_name
# 语法2: 使用花括号
${var_name}
# 区别: 花括号方式适合拼接字符串

  • variable deletion

grammar

unset var_name

demo

custom constant

introduce

A variable that cannot be modified after the variable is set is called a constant, also called a read-only variable

grammar

readonly var_name

demo

 

custom global variable

Introduction to the father-son shell environment

For example: there are 2 shell script files A.sh and B.sh

If the B.sh script file is executed in the A.sh script file, then A.sh is the parent shell environment, and B.sh is the child shell environment

Introduction to custom global variables

It is to define a global variable in the current script file. This global variable can be used in both the current shell environment and the sub-shell environment.

Custom global variable syntax

export var_name1 var_name2

Case requirements

  • Test whether global variables are available in the child shell and whether they are available in the parent shell

Case demonstration

  1. Create demo2.sh and demo3.sh files

  2. Edit demo2.sh, define the variable VAR4 and set it as global, and execute the demo3.sh script file inside

    vim demo2.sh

  3. Edit demo3.sh, print VAR4 inside

    vim demo3.sh

  4. Execute the script file demo2.sh and observe the effect of printing VAR4

  5. After executing the script file, print VAR4 in the interactive shell environment, and observe the effect of printing VAR4

 

in conclusion

Global variables are available in the current shell environment and sub-shell environment, but not in the parent shell environment

Add/delete/modify/check custom variables

Definitions and Modifications:var_name=value

Inquire:${var_name} 或 $var_name

delete:unset var_name


Shell Variables: Special Variables

Special variable: $n

grammar

$n

meaning

用于接收脚本文件执行时传入的参数
$0 用于获取当前脚本文件名称的
$1~$9, 代表获取第一输入参数到第9个输入参数
第10个以上的输入参数获取参数的格式: ${数字}, 否则无法获取

Execute script file incoming parameter syntax

sh 脚本文件 输入参数1 输入参数2 ...

Special variable: $#

grammar

$#

meaning

Get the number of all input parameters

Special variables: $*,$@

grammar

$*
$@
# 含义都是获取所有输入参数, 用于以后输出所有参数

$*with $@difference

1.不使用双引号括起来, 功能一样
  $*和$@获取所有输入参数,格式为: $1 $2 ... $n
2.使用双引号括起来
  "$*"获取的所有参数拼接为一个字符串, 格式为: "$1 $2 ... $n"
  "$@"获取一组参数列表对象, 格式为: "$1" "$2" ... "$n"
  使用循环打印所有输入参数可以看出区别

loop syntax

for var in 列表变量
do      # 循环开始
   命令  # 循环体
done    # 循环结束

Case requirements

Print out all input parameters in a loop in demo4.sh, experience $*the $@difference with

Implementation steps

Edit the demo4.sh script file

增加命令: 实现直接输出所有输入后参数
增加命令: 使用循环打印输出所有输入参数

demo

  1. Edit the demo4.sh file

  2. Directly output all input parameters, and loop output all input parameters (use double quotes to include $*and $@)

    #!/bin/bash
    # 命令1: 打印当前脚本文件名字
    echo "当前脚本文件名称:$0"
    ​
    # 命令2: 打印第1个输入参数
    echo "第一个输入参数:$1"
    ​
    # 命令3: 打印第2个输入参数
    echo "第二个输入参数:$2"
    ​
    # 命令4: 打印第10个输入参数
    echo "第十个输入参数不带花括号获取:$10"
    echo "第十个输入参数带花括号获取:${10}"
    ​
    # 命令5 打印所有输入参数的个数
    echo "所有输入参数个数:${#}"
    ​
    ​
    # 增加命令: 实现直接输出所有输入后参数
    echo '使用$*直接输出:'$*
    echo '使用$@直接输出:'$@
    ​
    # 增加命令: 使用循环打印输出所有输入参数
    echo '循环遍历输出$*所有参数'
    for item in "$*"
    do
       echo $item
    done
    echo '循环遍历输出$@所有参数'
    for item in "$@"
    do
       echo $item
    done

  3. Running Watch Differences

Special variable: $?

grammar

$?

meaning

Used to get the exit status code of the last shell command, or the return value of a function

The execution of each Shell command has a return value, which is used to indicate whether the command execution was successful or not.

Generally speaking, returning 0 means the command was executed successfully, and non-0 means the execution failed

demo

Enter a correct command, and then output$?

Enter an error command, in the output$?

Special variable: $$

grammar

$$

meaning

Process ID number used to get the current shell environment

demo

View the current shell environment process number

ps -aux|grep bash

Output $$ displays the current shell environment process number

summary

Commonly used special symbol variables are as follows

special variable meaning
$n To get input parameters $0, get the name of the current shell script file $1~$9, get the first input parameter to the ninth input parameter, and use curly braces ${10}to get 10 and more parameters
$# Get the number of all input parameters
$*and$@ The difference between getting all input parameter data: If double quotes are not used, the function is the same, and all parameter data are obtained as a string. If double quotes are used, $@the parameter list object is obtained, and each parameter is an independent string.
$? Get the exit status code of the previous command, generally; 0 means the command succeeded, non-0 means the execution failed
$$ Get the ID number of the current shell environment process

Guess you like

Origin blog.csdn.net/qq_21402983/article/details/124071024