Linux Shell 入门(一)

#!/bin/bash

LOG_DIR=/var/log
ROOT_UID=0
LINES=50
E_XCD=66
E_NOTROOT=67

if [ "$UID" -ne "$ROOT_UID" ]
then
	echo "Must be root to run the script"
	exit $E_NOTROOT
fi

if [ -n "$1" ]
then
    lines=$1
else
    lines=$LINES
fi

cd $LOG_DIR
if ['pwd' != "$LOG_DIR" ]
then
    echo "Can not change to $LOG_DIR."
    exit $E_XCD
fi

tail -$lines messages > mesg.temp
mv mesg.temp messages

cat /dev/null > wtmp

echo "Logs cleaned up.";
exit 0






有时候,如果想参数化子程序,可以这样写

#!/bin/bash
W_WRONG_ARGS=65
script_param="-a -h -m -z"
number_of_expected_args=3

if [ $# -ne $number_of_expected_args ]
then
    echo "Usage: 'basename $0' $script_param"
    exit $W_WRONG_ARGS
fi


字符串比较时,引用变量记得加上引号,不然可能由于变量中的空格导致Too many arguments错误

#!/bin/sh
myvar="foo bar oni"
if [ "$myvar" = "foo bar oni" ]; then
    echo "yes"
fi


打印出指定目录下所有文件和目录

#!/bin/bash
for myfile in `find /etc/` 
do
    if [ -d "$myfile" ]
    then
        echo "${myfile}(dir)"
    else
        echo "${myfile}"
    fi
done


引用参数

#!/bin/bash

for x in "$@"
do
    echo "you typed $x"
done

计算出1-100的和

#!/bin/bash

sum=0
i=1

while [ $i -lt 100 ]
do
    sum=$(( $sum + $i ))
    i=$(( $i + 1 ))
done

echo "SUM=${sum}"

case in语句

#!/bin/bash

if [ ! -n $1 ]; then
    echo "Usage: `basename $0` filename"
fi

case "${1##*.}" in
    gz)        
        echo "压缩文件"
        ;;
    txt)
        echo "文本文件"
        ;;
    sh)
        echo "bash 脚本文件"
        ;;
    *)
        echo "其他文件"
        ;;
esac
    


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值