Shell script uses the command interpretation function of Shell to parse a plain text file and then execute these functions. It can also be said that Shell script is a collection of a series of commands.
Shell can be used directly on win/Unix/Linux, and can call a large number of internal system functions to interpret and execute programs. If you are proficient in Shell scripts, it will make it easier for us to operate the computer and save a lot of time.
Shell application scenarios
What Shell can do
Simplify some complex commands (usually we may need to submit the github code once There are many steps, but it can be simplified into one step using Shell)
You can write some scripts to automatically replace the latest sdk (library) in a project
Automatic packaging, compilation, publishing and other functions
Clean up empty folders in the disk
In short, you can try all regular live scripts
What Shell can’t do
When precise calculations are required
The language needs to be very efficient When it is high
When some network operations are required
In short, Shell can quickly develop a script to simplify the development process, and cannot be used Alternative high-level language
How Shell works
Shell can be called a scripting language because it does not require compilation itself, but is interpreted through After the compiler interprets it, it compiles and executes it. Compared with traditional languages, there is an extra interpretation process, so the efficiency will be slightly worse than traditional directly compiled languages.
The simplest script:
#!/bin/bashecho "Hello World"
Just open the text editing tool, edit it as above, and then save it as test.sh
Run the script:
1. cd 到该目录下2. chmod +x ./test.sh #给脚本权限3. ./test.sh #执行脚本
In this way we wrote the first The simplest script, below we can try to write some complex scripts.
Variables in Shell
myText="hello world"muNum=100
What needs to be noted here is that there cannot be spaces before and after "=", and the naming rules are the same as in other languages.
Access variables
myText="hello world"muNum=100echo $myTextecho muNum
When you want to access variables, you need to use $, otherwise the output will be plain text, as shown in the figure below.

Four arithmetic operations in Shell
Example program
#!/bin/bashecho "Hello World !"a=3b=5val=`expr $a + $b`echo "Total value : $val"val=`expr $a - $b`echo "Total value : $val"val=`expr $a \* $b`echo "Total value : $val"val=`expr $a / $b`echo "Total value : $val"
What needs to be noted here is that when defining a variable, there cannot be spaces before and after "=", but when performing four arithmetic operations, there must be spaces before and after the operation symbols. When doing multiplication, Needs to be escaped.

Other operators =,==,!=,! , -o, -a
Example program
a=3b=5val=`expr $a / $b`echo "Total value : $val"val=`expr $a % $b`echo "Total value : $val"if [ $a == $b ]then echo "a is equal to b"fiif [ $a != $b ]then echo "a is not equal to b"fi

Relational operators
!/bin/shExample program
a=10b=20if [ $a -eq $b ]then echo "true"else echo "false"fiif [ $a -ne $b ]then echo "true"else echo "false"fiif [ $a -gt $b ]then echo "true"else echo "false"fiif [ $a -lt $b ]then echo "true"else echo "false"fiif [ $a -ge $b ]then echo "true"else echo "false"fiif [ $a -le $b ]then echo "true"else echo "false"fi

字符串运算符


字符串
#!/bin/shmtext="hello" #定义字符串 mtext2="world"mtext3=$mtext" "$mtext2 #字符串的拼接echo $mtext3 #输出字符串echo ${#mtext3} #输出字符串长度echo ${mtext3:1:4} #截取字符串

数组
#!/bin/sharray=(1 2 3 4 5) #定义数组 array2=(aa bb cc dd ee) #定义数组 value=${array[3]} #找到某一个下标的数,然后赋值echo $value #打印 value2=${array2[3]} #找到某一个下标的数,然后赋值echo $value2 #打印 length=${#array[*]} #获取数组长度echo $length

输出程序
echo
#!/bin/shecho "hello world" echo hello world text="hello world"echo $textecho -e "hello \nworld" #输出并且换行echo "hello world" > a.txt #重定向到文件echo `date` #输出当前系统时间

printf
同c语言,就不过多介绍了
判断语句
if
if-else
if-elseIf
case
#!/bin/sha=10b=20if [ $a == $b ]then echo "true"fiif [ $a == $b ]then echo "true"else echo "false"fiif [ $a == $b ]then echo "a is equal to b"elif [ $a -gt $b ]then echo "a is greater than b"elif [ $a -lt $b ]then echo "a is less than b"else echo "None of the condition met"fi

test命令
test $[num1] -eq $[num2] #判断两个变量是否相等 test num1=num2 #判断两个数字是否相等
for循环
#!/bin/shfor i in {1..5}doecho $idonefor i in 5 6 7 8 9doecho $idonefor FILE in $HOME/.bash*do echo $FILEdone
<code class="bash"><span class="hljs-meta"><br/><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/e287dce1bca30a9896dc8bd2ecb0e156-15.png?x-oss-process=image/resize,p_40" class="lazy" alt=""/></span></code>
while循环
#!/bin/shCOUNTER=0while [ $COUNTER -lt 5 ]doCOUNTER=`expr $COUNTER + 1`echo $COUNTERdoneecho '请输入。。。'echo 'ctrl + d 即可停止该程序'while read FILMdoecho "Yeah! great film the $FILM"done
以上是while循环的两种用法,第一种是比较常规的,执行循环,然后每次都把控制的数加1,就可以让while循环有退出的条件了。
第二种是用户从键盘数据,然后把用户输入的文字输出出来。
跳出循环
break #跳出所有循环 break n #跳出第n层f循环 continue #跳出当前循环
函数
#!/bin/shsysout(){echo "hello world"} sysout
定义一个没有返回值的函数,然后调用该函数
#!/bin/shtest(){ aNum=3anotherNum=5return $(($aNum+$anotherNum)) } test result=$?echo $result
定义一个有返回值的函数,调用该函数,输出结果

#!/bin/shtest(){echo $1 #接收第一个参数echo $2 #接收第二个参数echo $3 #接收第三个参数echo $# #接收到参数的个数echo $* #接收到的所有参数 } test aa bb cc
定义了一个需要传递参数的函数

重定向
$echo result > file #将结果写入文件,结果不会在控制台展示,而是在文件中,覆盖写 $echo result >> file #将结果写入文件,结果不会在控制台展示,而是在文件中,追加写echo input
写一个自动输入命令的脚本
自动提交github仓库的脚本
#!/bin/bashecho "-------Begin-------"git add . git commit -m $1echo $1git push origin masterecho "--------End--------"

以上便是我对shell知识的总结,欢迎大家点心,评论,一起讨论~~
The above is the detailed content of How should shell scripts be used?. For more information, please follow other related articles on the PHP Chinese website!

The core components of Linux include the kernel, file system, shell and common tools. 1. The kernel manages hardware resources and provides basic services. 2. The file system organizes and stores data. 3. Shell is the interface for users to interact with the system. 4. Common tools help complete daily tasks.

The basic structure of Linux includes the kernel, file system, and shell. 1) Kernel management hardware resources and use uname-r to view the version. 2) The EXT4 file system supports large files and logs and is created using mkfs.ext4. 3) Shell provides command line interaction such as Bash, and lists files using ls-l.

The key steps in Linux system management and maintenance include: 1) Master the basic knowledge, such as file system structure and user management; 2) Carry out system monitoring and resource management, use top, htop and other tools; 3) Use system logs to troubleshoot, use journalctl and other tools; 4) Write automated scripts and task scheduling, use cron tools; 5) implement security management and protection, configure firewalls through iptables; 6) Carry out performance optimization and best practices, adjust kernel parameters and develop good habits.

Linux maintenance mode is entered by adding init=/bin/bash or single parameters at startup. 1. Enter maintenance mode: Edit the GRUB menu and add startup parameters. 2. Remount the file system to read and write mode: mount-oremount,rw/. 3. Repair the file system: Use the fsck command, such as fsck/dev/sda1. 4. Back up the data and operate with caution to avoid data loss.

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

This guide will guide you to learn how to use Syslog in Debian systems. Syslog is a key service in Linux systems for logging system and application log messages. It helps administrators monitor and analyze system activity to quickly identify and resolve problems. 1. Basic knowledge of Syslog The core functions of Syslog include: centrally collecting and managing log messages; supporting multiple log output formats and target locations (such as files or networks); providing real-time log viewing and filtering functions. 2. Install and configure Syslog (using Rsyslog) The Debian system uses Rsyslog by default. You can install it with the following command: sudoaptupdatesud

When choosing a Hadoop version suitable for Debian system, the following key factors need to be considered: 1. Stability and long-term support: For users who pursue stability and security, it is recommended to choose a Debian stable version, such as Debian11 (Bullseye). This version has been fully tested and has a support cycle of up to five years, which can ensure the stable operation of the system. 2. Package update speed: If you need to use the latest Hadoop features and features, you can consider Debian's unstable version (Sid). However, it should be noted that unstable versions may have compatibility issues and stability risks. 3. Community support and resources: Debian has huge community support, which can provide rich documentation and

This article describes how to use TigerVNC to share files on Debian systems. You need to install the TigerVNC server first and then configure it. 1. Install the TigerVNC server and open the terminal. Update the software package list: sudoaptupdate to install TigerVNC server: sudoaptinstalltigervnc-standalone-servertigervnc-common 2. Configure TigerVNC server to set VNC server password: vncpasswd Start VNC server: vncserver:1-localhostno


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function