typora/note/Shell/流程控制.md
2024-12-12 10:48:55 +08:00

2.2 KiB
Raw Blame History

概览

  • if 结构
  • if else 结构
  • if elif else 结构
  • 层层嵌套

if 结构

if [ condition ];then
		command
		command
fi

if test condition;then
		command
fi

if [[ condition ]];then
		command
fi

# 等价于
[ condition ] && command

if else 结构

if [ condition ];then
		command1
	else
		command2
fi

# 等价于
[ condition ] && command1 || command2
me@me-EQ59:~/shell_demo/scripts/shell01$ cat if1.sh
#! /bin/env bash

# S1 输入参数的第一个 
if [ "$1" = "hello" ];then
	echo $1
else
	echo "world"
fi
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if1.sh
world
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if1.sh  hello
hello
me@me-EQ59:~/shell_demo/scripts/shell01$
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if_read.sh
请输入hello:hello
world
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if_read.sh
请输入hello:world
再次运行后请输入hello
me@me-EQ59:~/shell_demo/scripts/shell01$ cat if_read.sh
#! /bin/env bash

read -p "请输入hello:" str
if [ "$str" = "hello" ];then
	echo "world"
else
	echo "再次运行后请输入hello"
fi
me@me-EQ59:~/shell_demo/scripts/shell01$
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if_read_oneline.sh
please input hello:hello
hello
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if_read_oneline.sh
please input hello:world
please input hello!
me@me-EQ59:~/shell_demo/scripts/shell01$ cat if_read_oneline.sh
#! /bin/env bash
read -p "please input hello:" str; [ "$str" = "hello" ] && echo "hello" || echo "please input hello!"
me@me-EQ59:~/shell_demo/scripts/shell01$

if elif else结构

if [ condition1 ];then
		command1
		elif [ condition2 ];then
				command2
		elif [ condition3 ];then
			else
				command3
fi
me@me-EQ59:~/shell_demo/scripts/shell01$ cat if_elif.sh
#! /bin/env bash

read -p "请输入hello" str
if [ "$str" = "hello" ];then
	echo "hello"
elif [ "$str" = "hello_elif" ];then
	echo "hello_elif"
else
	echo "world"
fi

me@me-EQ59:~/shell_demo/scripts/shell01$ ./if_elif.sh
请输入hellohello
hello
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if_elif.sh
请输入hellohello_elif
hello_elif
me@me-EQ59:~/shell_demo/scripts/shell01$ ./if_elif.sh
请输入hellonothing
world
me@me-EQ59:~/shell_demo/scripts/shell01$