Shell programming file testing and if multi-branch statements

Source: Internet
Author: User

File Test usage:

    -e :判断文件是否存在,如果不存在返回的状态为假    -f :判断文件是否为普通文件    -d :判断是否为目录    -x :判断当前用户是否可执行此文件    -w :判断当前用户是否可写此文件    -r :判断当前用户是否可读此文件    如 [   -e  /etc/inittab    ]

If multi-branch statement

    if 条件一 ;then        执行语句    elif 条件二 ;then    执行语句    。。。    else        执行语句    fi

Write a script, given a file: if it is a normal file, print this is file. If it is a directory, print this is directory. Otherwise, this is an unrecognized file; The script reads as follows:
#!/bin/bash

    FILE=$1    #$1是位置变量,表示接受脚本后面接的第一个参数,$2,$3 ...表示接第二,三...个参数    #如果后面接的不止一个参数,只取第一个参数。    # $# 是特殊变量,获取参数的个数($* 列出所有参数),如过参数小于一个,就exit 1 退出,退出时带上退出状态码1,    # 如果不加上退出状态码,它默认的退出状态码就会以上一条命令的执行状态为准。    NUM=$#    if [ $NUM -lt 1 ];then        echo "脚本后面需接一个参数,如:judge.sh /etc/passwd ."        exit 1    fi    if [ -f $FILE  ];then        echo "this is file."    elif [ -d $FILE ];then        echo "this is directory."    else        echo "无法识别此文件."    fi

It is also important to note that if the parameter is less than one or two can be used $1,$2 ..., then if there are dozens of hundred? We can't use a lot of $ $ ... now we're going to use the shift statement, like shift 1, which means that the first argument is discarded, the second argument is treated as the first argument, and so on. The following script:
#!/bin/bash
echo $
Shift 1
echo $
Shift 1
echo $
Shift 1
echo $

Execution Result:

    [[email protected] ~]# sh shift.sh 1 2 3 4    1    2    3    4

In addition, if you want to debug the script, you can use Bash-x xxx.sh to print out the execution of the script to facilitate the identification of errors.

Shell programming file testing and if multi-branch statements

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.