Linux SHELL脚本

在Linux系统中,虽然有各种各样的图形化接口工具,但是sell仍然是一个非常灵活的工具。Shell不仅仅是命令的收集,而且是一门非常棒的编程语言。可以通过使用shell使大量的任务自动化,shell特别擅长系统管理任务,尤其适合那些易用性、可维护性和便携性比效率更重要的任务。 

以下为部分简单的shell脚本示例

 

--------------script----------------
#!/bin/bash
echo "hello world"
echo "the time is : $(date)"
echo "Let's see who's logging into the system:"
who
echo 'The price is $100'


--------------script----------------
#! /bin/bash

days=10
guest="kaite"
echo "$guest checked in $days ago"
days=5
guest="jessica"
echo "$guest checked in $days ago"


--------------script----------------
#! /bin/bash

value1=10
value2=$value1

echo The resulting value is $value2


--------------script----------------
#! /bin/bash
var1=100
var2=50
var3=45

echo "VAR1=$var1"
echo "VAR2=$var2"
echo "VAR3=$var3"
echo "VAR1+VAR2=$[$var1 + $var2]"
echo "VAR2-VAR3=$[$var2 - $var3]"
echo "VAR1-VAR3*2=$[$var1 - $var3*2]"


--------------script----------------
#! /bin/bash

for stop in 'ShangHai Hongqiao' Nanjing Xuzhou
do
  echo Next stop is $stop
done


--------------script----------------
#! /bin/bash

for NAME in 'jarry' 'harry' 'natasha'
do
  useradd $NAME &>/dev/null
  echo 'redhat' | passwd --stdin $NAME &> /dev/null
done


--------------script----------------
#! /bin/bash
# 编辑以下脚本,分析会输出什么结果以及这个脚本如何使用,并验证(这个脚本中用到了特殊变量--位置参数)

echo the first number is $1
echo the second number is $2
echo the sum is $[$1+$2]


--------------script----------------
#! /bin/bash

for Input in "$@"
do
  echo $Input
done


--------------script----------------
#! /bin/bash

FIRST=$1
SECOND=$2

if [ $FIRST -gt $SECOND ]
  then
  echo "First > Second"
fi

if [ $FIRST -lt $SECOND ]
  then
  echo "First < Second"
fi

if [ $FIRST -eq $SECOND ]
  then
  echo "First = Second"
fi


--------------script----------------
#! /bin/bash

FIRST=$1
SECOND=$2

if [ -z $FIRST ] || [ -z $SECOND ]
then
echo "Your Input is not complete"

elif [ $FIRST -gt $SECOND ]
  then
  echo "First > Second"
elif [ $FIRST -lt $SECOND ]
  then
  echo "First < Second"
else
  echo "First = Second"
fi


--------------script----------------
#! /bin/bash
#编辑一个脚本,实现如果用户输入参数 foo,则显示 bar,输入参数 bar,则显示 foo, 如果输入其他参数,则显示 error

case $1 in
"foo") 
    echo "bar";;
"bar")
    echo 'foo' 
    echo 'foo1' 
    echo 'foo2' ;;
*) echo 'error';;
esac


--------------script----------------
#! /bin/bash
#创建 file 文件中所列出的用户,并且所有用户的密码都是 redhat,这个脚本不检查参数的完整性


for NAME in $(cat $1)
do
  useradd $NAME &> /dev/null
  echo 'redhat' | passwd --stdin $NAME &> /dev/null
done


--------------script----------------
#! /bin/bash
# 创建一个脚本,实现与test13脚本的同样功能,但如果没有参数(只有脚本命令没有文件名), 则显示“Parameter error”,如果文件多于一个,则显示 parameters too long...,只有这个脚本后的文件名有且只有一个时脚本才本正确执行
if [ "$#" -gt 1 ]
  then
echo 'parameters too long...'
exit 1
fi

if [ ! -f "$1" ] ; then
echo 'file do not exist'
exit 1
fi

for NAME in $(cat $1)
do
  useradd $NAME &> /dev/null
  echo 'redhat' | passwd --stdin $NAME &> /dev/null
done

 

posted @ 2016-11-01 17:18  北海悟空  阅读(311)  评论(0编辑  收藏  举报