您的位置:首页 > 运维架构 > Shell

shell 学习笔记(1) - 基础

2017-12-07 11:02 337 查看

三种条件判断方式

test “$message” = “Hello”

[ $message” = “Hello” ]

[[ $message” == “Hello” ]] bash 内置 (常用)

字符串比较 - 条件式

str1 == str2

str1 != str2

-z str1 字符串为空

-n str1 字符串不为空

str1 == 模式 模式匹配

str1 != 模式 模式不匹配

数值比较 - 条件式

num1 -eq num2 相等

num1 -ne num2 不相等

num1 -lt num2 小于

num1 -le num2 小于等于

num1 -gt num2 大于

num1 -ge num2 大于等于

文件检查 - 条件式

-e 文件存在

-d 目录

-h 符号链接

-f 常规文件

逻辑运算 - 条件式

cond1 && cond2 都成立

cond1 || cond2 至少一个成立

!cond1 不成立

true

false

示例1

#!/bin/sh
if grep "hello" /tmp/tmp0 > /dev/null 2>&1; then
echo "hello world"
fi
# 或
grep "hello" /tmp/tmp0 > /dev/null 2>&1
rc = $?
if [[ $rc -eq 0 ]]; then
echo "hello world"
fi
# grep 如果找到 返回0
# shell 0 为真


数组使用

数组定义

arr=(a b c)



arr[0]=”a”

arr[1]=”b”

arr[2]=”c”

${arr[@]} 整个数组

${#arr[@]} 数组元素个数

示例

#!/bin/sh
echo $0
for item in "$@"; do
echo $item
done
# ./params.sh one two three
# 输出
# one
# two
# three


命令置换和数值运算

# message="sh 命令的完整路径是$(which sh)
# echo $message
# 输出
# sh 命令的完整路径是/bin/sh


$(command) 命令执行结果后置换为字符串

#!/bin/sh
fisrt=$1
step=$2
last=$3

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


$((operation)) 数值计算, 不需内部再加$符号

示例

#!/bin/sh
menu=("apple" "orange" "grape")
PS3="Which like?"
select item in ${menu[@]}; do
echo "Like $item"
done


注: ubuntu 中 执行sh srcipt.sh 会出错

./srcipt 不会错

因为ubuntu中sh 实际是dash
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell