条件判断3

多分支的if语句
if ...; then
 statement1
 ....
elif ...; then
 statement2
 ...
elif ...; then
  statement3
  ....
else 
  statement4
if
可以判断脚本错误的小命令

bash -n tx.sh

判断脚本一步一步的错误(一步一步执行结果回馈)

bash -x

$ bash -x tx.sh 
+ filename=/etc/passw
+ '[' '!' -e /etc/passw ']'
+ echo 'no /etc/passw'
no /etc/passw
+ exit 1

练习
如果一个文件不存在,退出
如果存在,判断为普通,或者目录,或者未知

#!/bin/bash
#
file=/etc/passwd
if [ ! -e $file ]; then
  echo "no $file"
  exit 1
fi

if [ -f $file ]; then 
  echo "$file is a common file."
elif [ -d $file ];then 
  echo "$file is a dir."
else
  echo "unknown file."
fi

$ bash -x 11_1.sh 
+ file=/etc/passwd
+ '[' '!' -e /etc/passwd ']'
+ '[' -f /etc/passwd ']'
+ echo '/etc/passwd is a common file.'
/etc/passwd is a common file.



#!/bin/bash
#
file=/etc/
if [ ! -e $file ]; then
  echo "no $file"
  exit 1
fi

if [ -f $file ]; then 
  echo "$file is a common file."
elif [ -d $file ];then 
  echo "$file is a dir."
else
  echo "unknown file."
fi

$ ./11_1.sh 
/etc/ is a dir.
位置变量,

$1 $2 ...
shift 完成一个命令就给他踢出去

在脚本里实现不定义文件,文件为变量

#!/bin/bash
#
if [ -e $1 ];then
  echo "OK"
else 
  echo "No"
fi

$ chmod +x weizhi.sh 
$ ./weizhi.sh /etc/passwd
OK
$ ./weizhi.sh /etc/pas
No


#shift 

#!/bin/bash
#

echo "$1"
shift
echo "$1"
shift
echo "$1"
shift

$ ./shift.sh 1 23 3
1
23
3

特殊变量

$# 变量个数,1个就返回1,0个文件返回为0,
所以没有设置文件返回为0,我们就可以退出脚本
$*参数个数

#!/bin/bash
#

if [ $# -lt 1 ];then 
 echo " warnings, plz usage: ./weizhi.sh AGR1 "
 exit 1
fi 

if [ -e $1 ];then
  echo "OK"
else 
  echo "No"
fi

$ ./weizhi.sh 
warning plz usage: ./weizhi.sh AGR1

练习,输入2个变量,求和 和 乘积

#!/bin/bash
#

if [ $# -lt 2 ];then 
echo "warnings, plz enter 2 numbers"
exit 2
fi

echo " the sum is $[$1+$2]"
echo " the pro is $[$1*$2]"

友情阅读推荐:

生信技能树公益视频合辑:学习顺序是linux,r,软件安装,geo,小技巧,ngs组学!

B站链接:https://m.bilibili.com/space/338686099

YouTube链接:https://m.youtube.com/channel/UC67sImqK7V8tSWHMG8azIVA/playlists

生信工程师入门最佳指南:https://mp.weixin.qq.com/s/vaX4ttaLIa19MefD86WfUA

学徒培养:https://mp.weixin.qq.com/s/3jw3_PgZXYd7FomxEMxFmw

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,846评论 0 10
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,483评论 0 5
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,678评论 25 708
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,995评论 2 59
  • 转眼已进入8月份,转眼也将立秋,这可是有史以来第一次8月份就立秋啊,可是我们的补课还有一半,今天仅仅是第1...
    李科杰阅读 137评论 0 0