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
Linux: A Look at Its Fundamental StructureLinux: A Look at Its Fundamental StructureApr 16, 2025 am 12:01 AM

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.

Linux Operations: System Administration and MaintenanceLinux Operations: System Administration and MaintenanceApr 15, 2025 am 12:10 AM

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.

Understanding Linux's Maintenance Mode: The EssentialsUnderstanding Linux's Maintenance Mode: The EssentialsApr 14, 2025 am 12:04 AM

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.

How Debian improves Hadoop data processing speedHow Debian improves Hadoop data processing speedApr 13, 2025 am 11:54 AM

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

How to learn Debian syslogHow to learn Debian syslogApr 13, 2025 am 11:51 AM

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

How to choose Hadoop version in DebianHow to choose Hadoop version in DebianApr 13, 2025 am 11:48 AM

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

TigerVNC share file method on DebianTigerVNC share file method on DebianApr 13, 2025 am 11:45 AM

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

Debian mail server firewall configuration tipsDebian mail server firewall configuration tipsApr 13, 2025 am 11:42 AM

Configuring a Debian mail server's firewall is an important step in ensuring server security. The following are several commonly used firewall configuration methods, including the use of iptables and firewalld. Use iptables to configure firewall to install iptables (if not already installed): sudoapt-getupdatesudoapt-getinstalliptablesView current iptables rules: sudoiptables-L configuration

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor