Operation and Maintenance
Linux Operation and Maintenance
How to use conditional statements in bash if case
How to use conditional statements in bash if case
In Bash scripts, if is suitable for simple logical judgment, and case is suitable for multi-value matching. 1. if is often used for dynamic condition judgments such as file existence and numerical comparison, and supports elif and else branch expansion; 2. case is more suitable for matching fixed values or patterns, such as classification processing of user input commands, supports wildcards and each branch must end with;; 3. Selection basis: use if for dynamic conditions, and case for fixed value matching.

In Bash scripts, if and case are two common ways to handle conditional judgments. They are each suitable for different scenarios: if is more suitable for simple logical judgments, while case is more suitable for matching multiple fixed values. Here are some practical uses and considerations.
Use if statements for conditional judgment
The if statement in Bash is usually used with test expressions. The basic structure is as follows:
if [condition]; then
# Execute command fi You can also add else or elif to extend the logic:
if [ condition1 ]; then
# Execute elif when condition 1 is true [ condition2 ]; then
# Execute else when condition 2 is true
# Execute fi when neither is trueCommon usage examples:
Check if the file exists:
if [ -f "filename.txt" ]; then echo "File exists" else echo "File does not exist" fiCompare numerical values:
if [ "$num" -gt 10 ]; then echo "The value is greater than 10" fi
Note: To compare strings, use = , and to compare numeric values, use operators such as -eq , -ne , -lt , -gt .
Use case statements for multi-value matching
When multiple situations need to be matched based on the value of a variable, case statement will be clearer and more concise. The syntax is as follows:
case $variable in
pattern1)
# Execute when pattern1 is matched;;
pattern2)
# Execute when pattern2 is matched;;
*)
#Default;;
esacPractical application scenarios:
For example, selecting an operation based on user input:
case $choice in
start)
echo "Start service"
;;
stop)
echo "stop service"
;;
restart)
echo "restart service"
;;
*)
echo "Invalid option"
;;
esacFeatures:
- Supports wildcards, such as
*.txt)that can match all file names ending in.txt. - Each branch must be added at the end
;;to indicate the end, otherwise the execution of the next branch will continue (similar to C's switch).
How to choose between if and case?
These two statements are not substitutes for each other, but have their own applicable scenarios:
-
Using if:
- The conditions are dynamic, such as numerical comparison, file status, etc.
- Not many logical branches and simple structure
-
When using case:
- To match multiple fixed values or patterns
- The input source is user input or configuration items with limited and unambiguous values.
For example:
- If you are determining whether the user input is
yesorno, you can useif - If you want to perform different operations based on the commands entered by the user (such as
start,stop,status), it is clearer to usecase
That's basically it. Mastering the use of if and case can make your Bash script more flexible and easier to maintain.
The above is the detailed content of How to use conditional statements in bash if case. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to manage software packages using Dnf and Rpm in Linux?
Mar 07, 2026 am 01:50 AM
dnfinstall prompts packagenotfound because it queries the enabled warehouse rather than the local installation status; rpm-q queries the local RPM database, and the scopes of the two are different.
How to monitor system performance and resources in Linux? (Top & Htop)
Mar 06, 2026 am 01:04 AM
The total top CPU usage is not 100% because it is calculated based on a single core, and the maximum is 800% for an 8-core system; the htop terminal size error needs to be fixed with eval$(resize); the real memory pressure is available rather than used; top command line truncation can be solved with the -c parameter.
How to setup file sharing using Samba on Linux? (SMB Protocol)
Mar 13, 2026 am 12:33 AM
The main reason why Windows cannot see the Samba share is that the firewall blocks UDP137–139/TCP445 or NetBIOS name resolution fails; it is necessary to confirm that the workgroup is consistent, the interfaces are configured correctly, the file permissions match forceuser/forcegroup, and set doscharset=UTF-8 to solve Chinese garbled characters.
How to extend a Logical Volume (LVM) in Linux without downtime?
Mar 13, 2026 am 12:53 AM
Logical volumes and file systems can be expanded online. You need to expand the LV first and then the file system. It is recommended to use lvextend-r for automatic synchronization adjustment, but you must ensure that the LVM and file system tool versions are compatible.
How to check open ports and listening services in Linux? (Netstat & SS)
Mar 10, 2026 am 01:08 AM
Netstat displays fewer LISTEN ports than ss because it does not display process information by default that non-root users do not have access to; ss can read all listening sockets by default without process names, and sudonetstat-tulpn is required to display them completely.
How to set up SSH key authentication on Linux? (Passwordless Login)
Mar 11, 2026 am 12:46 AM
It is recommended to use ssh-keygen-ted25519 to generate a key pair, because it is faster, more secure, and has a shorter key than the default RSA; it is necessary to strictly set the ~/.ssh directory permissions to 700 and authorized_keys to 600, and use ssh-v to confirm whether the client is Offering public key and whether the server rejects it.
How to format disk partitions using the command line in Linux?
Mar 15, 2026 am 12:01 AM
When fdisk is stuck at the Command prompt, it is normally waiting for input. Enter q to exit safely; you must umount before mkfs, otherwise it may fail silently; partedmkpart does not support the specified file system type, and mkfs needs to be executed separately.
How to configure a static IP address on Linux? (Netplan & NetworkManager)
Mar 14, 2026 am 12:02 AM
Netplan reports "InvalidYAML" when configuring a static IP due to indentation errors, missing spaces after colons, or mixed tabs; gateway4 has been deprecated and routes to:default must be used instead; NetworkManager needs to be modified before down/up takes effect; the renderer field is used to determine the backend during coexistence; incorrect DNS configuration will cause ping to succeed but curl to fail.





