search
HomeOperation and MaintenanceLinux Operation and MaintenanceClassic Thirteen Questions About Shell Scripts


Classic Thirteen Questions About Shell Scripts

1. Why is it called Shell?

We know that the operation of a computer is inseparable from hardware, but it cannot directly operate the hardware. The driver of the hardware can only be controlled by a software called "OS (Operating System)" .Strictly speaking, Linux is an operating system (OS).

Users have no way to directly operate the Kernel, but communicate with the Kernel through the Kernel's "shell" program, which is the so-called Shell. Shell is a The interactive interface (Interface) between the user and the system can only use the system to complete work through the command line (Command line). Therefore, the simplest definition of Shell is: Command Interpreter (Command Interpreter)

  • Translate the user's commands to the kernel for processing;

  • At the same time, translate the kernel processing results to the user.

Different OSs use different Kernels; on the same kernel, you can also use different Shells. Common Shells include sh, bash, csh, ksh, etc.

2. What is the relationship between Shell prompt (PS1) and Carriage Return (CR)?

After successfully logging in to a Shell terminal, the part to the left of the cursor is called the prompt. Usually, ordinary users use $, and administrator users use ##.

  • ##Shell Prompt: You can enter the command. After typing the command, wait until the CR (Carriage Return) character is read

  • Carriage Return: The command can be executed

From the technical details, the Shell will convert the Command line according to IFS (Internal Field Seperator) The entered text is broken down into "fields" (word/field). Then the special characters (meta) are processed first, and finally the entire command line is reorganized.

3. Others echo, and you also echo. How much do you know about echo?

echo sends argument to standard output (stdout), which is usually displayed on the screen.

stdin standard input
stdout standard output
stderr standard error output

echo -n  # 取消换行符
echo -e  # 启用反斜杠转译

4. What is the difference between double quotes "" and single quotes ''?

  • hard quote: '' (single quote), close all quotes

  • soft quote: "" (double quotation marks), keep the $ reference

5, var=value? What is the difference between export and before?

  • Variable definition: name=value, separators cannot be used on the left and right sides of the equal sign.

  • Variable substitution: echo ${name}

  • export变量:export name=value,使变量成为环境变量

# 本地变量
A=B
# 取消变量
unset A
# 环境变量export A=B

6、exec 跟 source 差在哪?

环境变量只能从父进程到子进程单向传递。换句话说:在子进程中环境如何变更,均不会影响父进程的环境。
当我们执行一个shell script时,其实是先产生一个sub-shell的子进程, 然后sub-shell再去产生命令行的子进程。关注Linux中文社区

# 创建子shell执行脚本
./1.sh
# 当前shell执行
source 1.sh
# 当前shell执行后退出
exec 1.sh

7、( ) 与 { } 差在哪?

( )将 command group 置于 sub-shell 执行
{ }则是在同一个shell内完成

8、$(()) 与 $() 还有 ${} 差在哪?

# 假设我们定义了一个变量为:
file=/dir1/dir2/dir3/my.file.txt
# 我们可以用 ${ } 分别替换获得不同的值:

# 1. shell字符串的非贪婪(最小匹配)左删除
${file#*/} # 拿掉第一条 / 及其左边的字符串:dir1/dir2/dir3/my.file.txt
# 2. shell字符串的贪婪(最大匹配)左删除
${file##*/} # 拿掉最后一条 / 及其左边的字符串:my.file.txt
${file##*.} # 拿掉最后一个 . 及其左边的字符串:txt
# 3. shell字符串的非贪婪(最小匹配)右删除:
${file%/*} # 拿掉最后条 / 及其右边的字符串:/dir1/dir2/dir3
${file%.*} # 拿掉最后一个 . 及其右边的字符串:/dir1/dir2/dir3/my.file
# 4. shell字符串的贪婪(最大匹配)右删除:
${file%%/*} # 拿掉第一条 / 及其右边的字符串:(空值)
${file%%.*} # 拿掉第一个 . 及其右边的字符串:/dir1/dir2/dir3/my

记忆的方法为:
# 是去掉左边(在键盘上 # 在 $ 之左边)
% 是去掉右边(在键盘上 % 在 $ 之右边)
单一符号是最小匹配﹔两个符号是最大匹配。

# 5. shell字符串取子串:
${file:0:5}:提取最左边的 5 个字节:/dir1
${file:5:5}:提取第 5 个字节右边的连续 5 个字节:/dir2

# 6. shell字符串变量值的替换:
${file/dir/path}:将第一个 dir 提换为 path:/path1/dir2/dir3/my.file.txt
${file//dir/path}:将全部 dir 提换为 path:/path1/path2/path3/my.file.txt

# 7. ${}还可针对变量的不同状态(没设定、空值、非空值)进行赋值:
${file-my.file.txt} :假如 $file 没有设定,则使用 my.file.txt 作传回值。(空值及非空值时不作处理) 
${file:-my.file.txt} :假如 $file 没有设定或为空值,则使用 my.file.txt 作传回值。(非空值时不作处理)
${file+my.file.txt} :假如 $file 设为空值或非空值,均使用 my.file.txt 作传回值。(没设定时不作处理)
${file:+my.file.txt} :若 $file 为非空值,则使用 my.file.txt 作传回值。(没设定及空值时不作处理)
${file=my.file.txt} :若 $file 没设定,则使用 my.file.txt 作传回值,同时将 $file 赋值为 my.file.txt 。(空值及非空值时不作处理)
${file:=my.file.txt} :若 $file 没设定或为空值,则使用 my.file.txt 作传回值,同时将 $file 赋值为 my.file.txt 。(非空值时不作处理)
${file?my.file.txt} :若 $file 没设定,则将 my.file.txt 输出至 STDERR。(空值及非空值时不作处理)
${file:?my.file.txt} :若 $file 没设定或为空值,则将 my.file.txt 输出至 STDERR。(非空值时不作处理)

tips:
以上的理解在于, 你一定要分清楚 unset 与 null 及 non-null 这三种赋值状态.
一般而言, : 与 null 有关, 若不带 : 的话, null 不受影响, 若带 : 则连 null 也受影响.

# 8. 计算shell字符串变量的长度:${#var}
${#var} 可计算出变量值的长度:
${#file} 可得到 27 ,因为 /dir1/dir2/dir3/my.file.txt 刚好是 27 个字节...

# 9. bash数组(array)的处理方法
数组:
A=(a b c d)
引用数组:
${A[@]}
${A[*]}
访问数组成员
${A[0]}
计算数组长度
${#A[@]}
${#A[*]}
数组重新赋值
A[2]=xyz

# 10.$(( ))是用来做整数运算的 
a=5;b=7;c=2;
echo $(( a + b * c))

9、$@ 与 $* 区别在哪?

  • "$@"则可得到 “p1” “p2 p3” “p4” 这三个不同的词段

  • "$*"You can get the entire string of single segments "p1 p2 p3 p4"

  • In addition, Search the public account Linux and this is how you should learn to reply "git books" in the background and get a surprise gift package.

##10. What is the difference between && and ||?

1. The test command has two forms

  • test expression

  • [ expression ]

2. Bash’s test currently supports three test objects

  • string: string

  • integer:integer

  • file:file

3、当 expression 为真是返回 0(true) ,否则返回 非0(false)

  • command1 && command2  command2 只有在 command1 的RV为0(True)的条件下执行。

  • command1 || command2  command2只有在command1的RV为非0(False)的条件下执行。

4、先替换变量再比较

A=123[ -n "$A" ] && ([ "$A" -lt 100 ] || echo "too big")unset A

11、> 与

0: Standard Input(STDIN)
1: Standard Output (STDOUT)
2: Standard Error Output(STDERR)

我们可用

我们可用 > 来改变送出的数据信道(stdout, stderr),使之输出到指定的档案。

ls my.file no.such.file 1> file.out 2>file.err
# 2>&1 就是将stderr并进stdout做输出
ls my.file no.such.file 1> file.out 2>&1
# /dev/null 空
ls my.file no.such.file >/dev/null 2>&1

cat < file > file
# 在 IO Redirection 中,stdout 与 stderr 的管道会先准备好,才会从 stdin 读进资料。
# 也就是说,在上例中,> file 会先将 file 清空,然后才读进 < file , 
# 但这时候档案已经被清空了,因此就变成读不进任何数据了

12、你要if还是case呢?

# if
echo -n "Do you want to continue?(Yes/No):"
read YN
if [ "$YN"=Y -o "$YN"=y -o "$YN"="Yes" -o "$YN"="yes" -o "$YN"="YES"];then
echo "continue"
else
exit 0
fi

# case
echo -n "Do you want to continue?(Yes/No):"
read YN
case "$YN" in
[Yy]|[Yy][Ee][Ss])
echo "continue"
;;
*)
exit 0
esac

13、for what? while与until差在哪?

# for
for ((i=1;i<=10;i++))
do
echo "num is $i"
done

# while
num=1
while [ "$num" -le 10 ]; do
echo "num is $num"
num=$(($num + 1))
done

# until
num=1
until [ "$num" -gt 10 ]; do
echo "num is $num"
num=$(($nu + 1))
done
  • break 是结束 loop

  • return 是结束 function

  • exit 是结束 script/shell

The above is the detailed content of Classic Thirteen Questions About Shell Scripts. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Linux中文社区. If there is any infringement, please contact admin@php.cn delete
The 5 Core Components of the Linux Operating SystemThe 5 Core Components of the Linux Operating SystemMay 08, 2025 am 12:08 AM

The five core components of the Linux operating system are: 1. Kernel, 2. System libraries, 3. System tools, 4. System services, 5. File system. These components work together to ensure the stable and efficient operation of the system, and together form a powerful and flexible operating system.

The 5 Essential Elements of Linux: ExplainedThe 5 Essential Elements of Linux: ExplainedMay 07, 2025 am 12:14 AM

The five core elements of Linux are: 1. Kernel, 2. Command line interface, 3. File system, 4. Package management, 5. Community and open source. Together, these elements define the nature and functionality of Linux.

Linux Operations: Security and User ManagementLinux Operations: Security and User ManagementMay 06, 2025 am 12:04 AM

Linux user management and security can be achieved through the following steps: 1. Create users and groups, using commands such as sudouseradd-m-gdevelopers-s/bin/bashjohn. 2. Bulkly create users and set password policies, using the for loop and chpasswd commands. 3. Check and fix common errors, home directory and shell settings. 4. Implement best practices such as strong cryptographic policies, regular audits and the principle of minimum authority. 5. Optimize performance, use sudo and adjust PAM module configuration. Through these methods, users can be effectively managed and system security can be improved.

Linux Operations: File System, Processes, and MoreLinux Operations: File System, Processes, and MoreMay 05, 2025 am 12:16 AM

The core operations of Linux file system and process management include file system management and process control. 1) File system operations include creating, deleting, copying and moving files or directories, using commands such as mkdir, rmdir, cp and mv. 2) Process management involves starting, monitoring and killing processes, using commands such as ./my_script.sh&, top and kill.

Linux Operations: Shell Scripting and AutomationLinux Operations: Shell Scripting and AutomationMay 04, 2025 am 12:15 AM

Shell scripts are powerful tools for automated execution of commands in Linux systems. 1) The shell script executes commands line by line through the interpreter to process variable substitution and conditional judgment. 2) The basic usage includes backup operations, such as using the tar command to back up the directory. 3) Advanced usage involves the use of functions and case statements to manage services. 4) Debugging skills include using set-x to enable debugging mode and set-e to exit when the command fails. 5) Performance optimization is recommended to avoid subshells, use arrays and optimization loops.

Linux Operations: Understanding the Core FunctionalityLinux Operations: Understanding the Core FunctionalityMay 03, 2025 am 12:09 AM

Linux is a Unix-based multi-user, multi-tasking operating system that emphasizes simplicity, modularity and openness. Its core functions include: file system: organized in a tree structure, supports multiple file systems such as ext4, XFS, Btrfs, and use df-T to view file system types. Process management: View the process through the ps command, manage the process using PID, involving priority settings and signal processing. Network configuration: Flexible setting of IP addresses and managing network services, and use sudoipaddradd to configure IP. These features are applied in real-life operations through basic commands and advanced script automation, improving efficiency and reducing errors.

Linux: Entering and Exiting Maintenance ModeLinux: Entering and Exiting Maintenance ModeMay 02, 2025 am 12:01 AM

The methods to enter Linux maintenance mode include: 1. Edit the GRUB configuration file, add "single" or "1" parameters and update the GRUB configuration; 2. Edit the startup parameters in the GRUB menu, add "single" or "1". Exit maintenance mode only requires restarting the system. With these steps, you can quickly enter maintenance mode when needed and exit safely, ensuring system stability and security.

Understanding Linux: The Core Components DefinedUnderstanding Linux: The Core Components DefinedMay 01, 2025 am 12:19 AM

The core components of Linux include kernel, shell, file system, process management and memory management. 1) Kernel management system resources, 2) shell provides user interaction interface, 3) file system supports multiple formats, 4) Process management is implemented through system calls such as fork, and 5) memory management uses virtual memory technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software