学习shell script

shell script 是利用shell 所写的一个程序,可以将shell的语法和命令,搭配正则表达式,管道命令,数据流重定向等完成我们所要处理的目的。

第一个shell 代码

#!bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e "Hello World! \a \n"
exit 0

第一行 #!bin/bash 声明这个script使用的shell名称。
程序打印 hello world 字符,exit 0 表示代码正常执行结束。

/bin目录(binary)是二进制执行文件目录,主要用于具体应用;
/sbin目录(system binary)是系统管理员专用的二进制代码存放目录,主要用于系统管理

输入变量

read -p "Please input your first name: " firstname
read -p "Please input your last name: " lastname

shell script可以要求用户输入变量。

输出变量

echo -e "\nYour full name is: $firstname $lastname ."

使用echo打印字符串,变量的值打印需要在变量名前加上$

test方法

当需要检测系统上某些文件或者相关属性时,可以利用test命令来检测。

test -f $filename && filetype="regular file"
test -d $filename && filetype="directory"
test -r $filename && perm="readable"
test -w $filename && perm="$perm writable"
test -x $filename && perm="$perm executable"

test命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。test的一些常用用法如图
这里写图片描述
这里写图片描述
这里写图片描述

if…then判断式

if [ "$yn"=="Y" ] || [ "$yn"=="y" ]; then
    echo "OK, continue"
    exit 0
fi

使用elif进行判断

if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
        echo "OK, continue"
        exit 0
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
        echo "Oh, interrupt!"
        exit 0
fi

case…esac

case $1 in
    "hello")
    echo "Hello, how are you?"
    ;;
    "")
    echo "You MUST input parameters, ex> {$0 someword}"
    ;;
    *)
    echo "Usage $0 {hello}"
    ;;
esac

function方法

printit(){
    echo -n "Your choice is "
}

echo "This program will print your selection! "
case $1 in
    "one")
    # echo "Your choice is ONE"
    printit; echo $1 | tr 'a-z' 'A-Z'
    ;;
    "two")
    # echo "Your choice is TWO"
    printit; echo $1 | tr 'a-z' 'A-Z'
    ;;
    "three")
    # echo "Your choice is THREE"
    printit; echo $1 | tr 'a-z' 'A-Z'
    ;;
    *)
    echo "Usage $0 {one|two|three}"
    ;;
esac

在ubuntu系统中,shell 函数的结构是

fname(){程序段}

在其他系统需要加上function 关键字。

function fname(){程序段}

循环

while do done, until do done

语法格式为

while [ condition ]
do
    程序段落
done

以及

unti [ condition ]
do
    程序段落
done 

举个例子

while [ "$yn" != "yes" -a "$yn" != "YES" ]
do 
    read -p "Please input yes/YES to stop this program: " yn
done

for…do…done

for animal in dog cat elepant
do 
    echo "There are $(animal)s..."
done
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值