shell

例一:if的三种写法

#!/bin/sh
message="Hello"

if test "$message" = "Hello"; then
    echo "hello world"
fi

if [ "$message" = "Hello" ]; then
        echo "hello world"
fi

if [[ $message == "Hello" ]];then
        echo "Hello world3"
fi

 sh是软连接bash,#!/bin/bash也可。

注意:【<条件式>】和【【<条件式>】】

<条件式>和这边的括号之间,==、=与左边的变量、右边的字符串之间都要有空格

变量是双引号里面,不是单引号。

例二:while循环

#!/bin/bash

first=$1
step=$2
last=$3

c=$first

while [[ $c -le $last ]];do
        echo $c
        c=$(( c + step ))
done

 例三、变量与连接字符串

#!/bin/sh

set -x
message="hello"
read name
set +x
echo "$message ,$name"
echo "${message}world"

例四:根据返回值来判断。或赋予一个变量

#!/bin/bash

if grep "hello" /home/shell/hello1.sh >/dev/null 2>&1; then
        echo "Hello world1"
fi

grep "hello" /home/shell/hello1.sh >/dev/null 2>&1
rc=$?
if [[ $rc -eq 0 ]]; then
        echo "hello world2"
fi

例五:$() 和$(())

#!/bin/sh
message="sh命令行的路径是$( which sh)"
echo $message

输出结果为:sh命令行的路径是/bin/sh

$()把命令行里面的取出来,当成变量来使用。

$(()) 也同理,不过最里面的括号不需要给变量附加$。如例二。

附录:if中的条件式如下:

1 字符串判断

str1 = str2      当两个串有相同内容、长度时为真 
str1 != str2      当串str1和str2不等时为真 
-n str1        当串的长度大于0时为真(串非空) 
-z str1        当串的长度为0时为真(空串) 
str1           当串str1为非空时为真

2 数字的判断

int1 -eq int2    两数相等为真 
int1 -ne int2    两数不等为真 
int1 -gt int2    int1大于int2为真 
int1 -ge int2    int1大于等于int2为真 
int1 -lt int2    int1小于int2为真 
int1 -le int2    int1小于等于int2为真

3 文件的判断

-r file     用户可读为真 
-w file     用户可写为真 
-x file     用户可执行为真 
-f file     文件为正规文件为真 
-d file     文件为目录为真 
-c file     文件为字符特殊文件为真 
-b file     文件为块特殊文件为真 
-s file     文件大小非0时为真 
-t file     当文件描述符(默认为1)指定的设备为终端时为真

3 复杂逻辑判断

-a         与 
-o        或 
!        非

原文地址:https://www.cnblogs.com/bluewelkin/p/4386750.html