Shell study notes (continuous)

Table of contents

Table of contents

0.Reference

1. Variables

1.Definition

2.Use

3. The difference between single quotes and double quotes

4. Variable assignment

5. Read-only variables

6. Delete variables

7. Scope local and global

8.export

2. Command substitution

3. Font color

4.if judgment

5. case judgment


0.Reference

Shell Programming — ShellScript 1.0.0 documentation

shell online Chinese manual abs, shell Chinese tutorial, shell Chinese tutorial - Undersea Goshawk (tank) blog

cplusplus.com - The C++ Resources Network

1. Variables

Shell variables: definition, assignment and deletion of Shell variables

1.Definition

# Shell 支持以下三种定义变量的方式:
variable=value
variable='value'
variable="value"

Note that there cannot be spaces= around the assignment number , which may be different from most programming languages ​​you are familiar with.

2.Use

To use a defined variable, just add a dollar sign in front of the variable name $.

#使用一个定义过的变量,只要在变量名前面加美元符号$即可,如:
author="严长生"
echo $author
echo ${author}
#变量名外面的花括号{ }是可选的,加不加都行,加花括号是为了帮助解释器识别变量的边界,比如下面这种情况:
skill="Java"
echo "I am good at ${skill}Script"
#如果不给 skill 变量加花括号,写成echo "I am good at $skillScript",
#解释器就会把 $skillScript 当成一个变量(其值为空),代码执行结果就不是我们期望的样子了。

It is recommended to put curly braces on all variables { }. This is a good programming habit.

3. The difference between single quotes and double quotes

#!/bin/bash
url="http://c.biancheng.net"
website1='C语言中文网:${url}'
website2="C语言中文网:${url}"
echo $website1
echo $website2

运行结果:
C语言中文网:${url}
C语言中文网:http://c.biancheng.net

When the value of a variable is surrounded by single quotes ' ', whatever is inside the single quotes will be output. Even if there are variables and commands in the content (commands need to be dequoted), they will be output as they are. This method is more suitable for defining the situation of displaying pure strings, that is, scenarios where you do not want to parse variables, commands, etc.   === 》corresponds to plain text.

When the value of a variable is surrounded by double quotes , the variables and commands inside" " will be parsed first during output , instead of outputting the variable names and commands in double quotes as they are. This method is more suitable for variable definitions that have variables and commands attached to the string and want to parse them and then output them. My suggestion: If the content of the variable is a number, you don’t need to add quotes; if you really need to output it as it is, add single quotes; other strings that have no special requirements are best to add double quotes, and add double quotes when defining variables. is the most common usage scenario.

4. Variable assignment

variable=`command`
variable=$(command)

第一种方式把命令用反引号` `(位于 Esc 键的下方)包围起来,
反引号和单引号非常相似,容易产生混淆,所以不推荐使用这种方式;
第二种方式把命令用$()包围起来,区分更加明显,所以推荐使用这种方式。

5. Read-only variables

#!/bin/bash
myUrl="http://c.biancheng.net/shell/"
readonly myUrl
myUrl="http://c.biancheng.net/shell/"

6. Delete variables

#!/bin/sh
myUrl="http://c.biancheng.net/shell/"
unset myUrl
echo $myUrl

#上面的脚本没有任何输出。

7. Scope local and global

Function: Generally used for the definition of local variables in the shell, mostly used inside functions

Regarding local variables and global variables:
(1) Variables defined in shell scripts are global , and their scope starts from the place where they are defined until the end of the shell or the place where they are deleted.
(2) The variables defined by the shell function are also global, and their scope starts from the place where the function is called to execute the variable, and ends when the shell is terminated or deleted. Variables defined by a function can be local, and their scope is limited to the function . But the parameters of the function are local.
(3) If the local variable and the global variable have the same name, then the local variable will be used inside this function.

8.export

export sets custom variables as system environment variables (limited to this login operation, valid in the current shell)

​​​​​​Shell export function - ze_zhang - Blog Park

If a variable is defined in a shell script, when the script is running, the defined variable is only a local variable within the script, and other shells cannot reference it. To make the value of a variable available in other If changed in the shell, you can use the export command to output the defined variables.

The export command will cause the system to define a copy of this variable when each new shell is created. This process is called variable output .

1. When executing the script, it is run in a subshell environment. After the script is executed, the subshell automatically exits;

2. The system environment variables in a shell will be copied to the subshell (variables defined by export);

3. The system environment variables in a shell are only valid for the shell or its subshells. The variables disappear when the shell ends
(and cannot be returned to the parent shell).

3. Variables defined without export are only valid for this shell and are invalid for subshells.

I sorted out the posts: Why are there different lines between direct execution of a script and execution using source? This is also a problem I encountered myself. The original text of the manual is as follows:

Read and execute commands from filename in the current shell environment and
return the exit status of the last command executed from filename.

Do you understand why it is different? Directly executing a script file is run in a subshell, while source is

Running in the current shell environment. Based on the previous content, you already understand the reason.

My understanding is: If you want the subshell to use variables, the main shell can define the variables first. For example, in the compilation script in our environment, the main shell determines tool chain, path and other information, and the subshell can use it directly, avoiding hard code.

2. Command substitution

variable=`commands`
variable=$(commands)

#!/bin/bash
begin_time=`date`    #开始时间,使用``替换
sleep 20s            #休眠20秒
finish_time=$(date)  #结束时间,使用$()替换
echo "Begin time: $begin_time"
echo "Finish time: $finish_time"

运行脚本,20 秒后可以看到输出结果:
Begin time: 2019年 04月 19日 星期五 09:59:58 CST
Finish time: 2019年 04月 19日 星期五 10:00:18 CST
#!/bin/bash
begin_time=`date +%s`    #开始时间,使用``替换
sleep 20s                #休眠20秒
finish_time=$(date +%s)  #结束时间,使用$()替换
run_time=$((finish_time - begin_time))  #时间差
echo "begin time: $begin_time"
echo "finish time: $finish_time"
echo "run time: ${run_time}s"

运行脚本,20 秒后可以看到输出结果:
begin time: 1555639864
finish time: 1555639884
run time: 20s

3. Font color

Word color: 30—–37 
  echo -e “\033[30m black words\033[0m” 
  echo -e “\033[31m red words \033[0m” 
  echo -e “\033[32m green words \033[ 0m" 
  echo -e "\033[33myellow characters \033[0m" 
  echo -e "\033[34mblue characters \033[0m" 
  echo -e "\033[35mpurple characters \033[0m" 
  echo - e “\033[36m sky blue characters \033[0m” 
  echo -e “\033[37m white characters\033[0m” 

character background color range: 40—–47 
  echo -e “\033[40;37m white characters on black background \033[0m” 
  echo -e “\033[41;37m White characters on a red background\033[0m” 
  echo -e “\033[42;37m White characters on a green background\033[0m” 
  echo -e “\033[43; 37m White characters on a yellow background\033[0m” 
  echo -e “\033[44;37m White characters on a blue background\033[0m” 
  echo -e “\033[45;37m Purple background with white characters\033[0m” 
  echo -e “\033[46;37m Sky blue background with white characters\033[0m” 
  echo -e “\033[47;30m White background with black characters \033[0m”

4.if judgment

Shell if else statement (detailed version)

#!/bin/bash

read a
read b

if (( $a == $b ))
then
    echo "a和b相等"
fi

# ===========================
if  condition
then
    statement(s)
fi

## 或者这样,多了一个 ;
if  condition;  then
    statement(s)
fi

5. case judgment

Detailed explanation of Shell case in statement - zhouyuqiang - Blog Park

#!/bin/bash
printf "Input integer number: "
read num
case $num in
    1)
        echo "Monday"
        ;;
    2)
        echo "Tuesday"
        ;;
    3)
        echo "Wednesday"
        ;;
    4)
        echo "Thursday"
        ;;
    5)
        echo "Friday"
        ;;
    6)
        echo "Saturday"
        ;;
    7)
        echo "Sunday"
        ;;
    *)
        echo "error"
esac

# ============================
# 总结起来就是
case expression in
    pattern1)
        statement1
        ;;
    pattern2)
        statement2
        ;;
    pattern3)
        statement3
        ;;
    # ……
    *)
        statementn
esac

Guess you like

Origin blog.csdn.net/scarlettsp/article/details/122938731