lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

bash:"IF command"命令作为条件

 

 

 

 

一、说明

 

  1、IF的条件部分,可以使用linux“命令”。

1 if command
2 then
3     command if $?=0
4 else
5     command if $?!=0
6 fi

 

 

 

 

二、代码

 

 1 [root@rocky shell]# cat  if_command 
 2 #!/usr/bin/env bash
 3 
 4 
 5 # file_name = if_command
 6 
 7 
 8 run()
 9 {
10         if $@
11         then
12                 echo "os_running: ${@}"
13         fi
14 }
15 
16 
17 list()
18 {
19         if  ls -lh      # command as condition of if
20         then
21                 echo
22         fi
23 }
24 
25 
26 
27 
28 run $@
29 
30 list
31 
32 
33 [root@rocky shell]# 
34 [root@rocky shell]# 

 

 

 

 

 

 

三、运行

 

 

 1 [root@rocky shell]# cat  if_command 
 2 #!/usr/bin/env bash
 3 
 4 
 5 # file_name = if_command
 6 
 7 
 8 run()
 9 {
10         if $@
11         then
12                 echo "os_running: ${@}"
13         fi
14 }
15 
16 
17 list()
18 {
19         if  ls -lh      # command as condition of if
20         then
21                 echo
22         fi
23 }
24 
25 
26 
27 
28 run $@
29 
30 list
31 
32 
33 [root@rocky shell]# 
34 [root@rocky shell]# 
35 [root@rocky shell]# ls
36 if_command
37 [root@rocky shell]# 
38 [root@rocky shell]# 
39 [root@rocky shell]# ./if_command "mkdir big"
40 os_running: mkdir big
41 total 4.0K
42 drwxr-xr-x 2 root root   6 Jan 29 00:01 big
43 -rwx--x--x 1 root root 192 Jan 28 23:59 if_command
44 
45 [root@rocky shell]# 
46 [root@rocky shell]# 
47 [root@rocky shell]# ls
48 big  if_command
49 [root@rocky shell]# 
50 [root@rocky shell]# 
51 [root@rocky shell]# rm -rf big
52 [root@rocky shell]# 
53 [root@rocky shell]# 
54 [root@rocky shell]# ls
55 if_command
56 [root@rocky shell]# 
57 [root@rocky shell]# 

 

 

 

 

 

 

四、参考资料

 

  1、  Bash - Conditional structures if and case:  https://docs.rockylinux.org/books/learning_bash/06-conditional-structures/

 

posted on 2023-01-28 23:56  lnlidawei  阅读(82)  评论(0编辑  收藏  举报