[Bash] Controls flow
If
The if statement is used to execute commands based on a condition.
if [ condition ]; then
commands
fi
Example: vim example.sh
#!/bin/zsh
echo "Enter a number: "
read number
if [ $number -gt 0 ]; then
echo "The number is positive."
elif [ $number -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi
chmod +x example.sh
Case
The case statement is used to execute commands based on multiple conditions.
case value in
pattern1)
commands1
;;
pattern2)
commands2
;;
*)
default_commands
;;
esac
Example
#!/bin/zsh
echo "Enter a letter: "
read letter
case $letter in
[a-z])
echo "You entered a lowercase letter."
;;
[A-Z])
echo "You entered an uppercase letter."
;;
*)
echo "You entered a non-alphabet character."
;;
esac
For
The for loop is used to iterate over a list of items.
for item in list; do
commands
done
Example:
#!/bin/zsh
for i in {1..5}; do
echo "Number: $i"
done
Pratices:
# Write an if statement to check if a file named myfile.txt exists and print a message accordingly.
FILENAME="myfile.txt"
if [ -f $FILENAME ]; then
echo "$FILENAME exists"
else
echo "No such file"
fi
# Write a case statement to check if a variable color is "red", "green", or "blue" and print a message for each color.
echo "Enter a color: "
read color
case $color in
red)
echo "red'
;;
blue)
echo "blue"
;;
green)
echo "green"
;;
*)
echo "not find a match color"
;;
# Write a for loop to print the names of all files in the current directory.
for file in *; do
if [ -f "$file" ]; then
echo "File: $file"
# size=$(stat -c%s "$file")
size=$(stat -f%z "$file")
echo "File: $file, Size: $size bytes"
fi
done
Output:
File: if.sh, Size: 105 bytes
File: list_regular_files.sh
File: list_regular_files.sh, Size: 162 bytes
You can check the file size by using ls -lh
as well
for file in *; do:
This loop iterates over all items in the current directory.
if [ -f "$file" ]; then:
Checks if the item is a regular file.
分类:
CLI
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-05-19 [Spring Data JPA] Derived Query Methods
2021-05-19 [AWS] DynamoDB: Designing Partition Keys to Distribute Your Workload Evenly
2020-05-19 [Cypress] Change a viewport width and height in a cypress test
2020-05-19 [SCSS] Access Theme Color Values With Sass
2019-05-19 [Spring Boot] Using @Around advice to implement performance tracing and @Pointcut for custom Annotation
2017-05-19 [AngularJS] Directive for top scroll bar