技术联盟

shell 脚本Demo

!/bin/bash

Author: zhangdongling

Copyright(C)

Script follows here:

echo “What is your name?”
read PERSON
echo “Hello ,$PERSON”


variableName=”zhangdl”
name=dong
echo “variableName,$variableName”
echo “name,$name”


echo “1.”$0 #当前脚本的文件名
echo “2.”$1 #传递给脚本或函数的参数
echo “3.”$# #传递给脚本或函数的参数个数。
echo “4.”$* #传递给脚本或函数的所有参数。
echo “5.”$@ #传递给脚本或函数的所有参数。被双引号(” “)包含时,与 $* 稍有不同,下面将会讲到。
echo “6.”$? #上个命令的退出状态,或函数的返回值。大部分命令执行成功会返回0,失败返回1
echo “7.”$$ #当前 Shell 进程 ID。
echo “8.\”$@\””
echo “9.\”$*\””
echo -e “pid is $$ \n”
echo “pid is $$ \n”


DATE=date
echo -e “DATE is $DATE \n”
USERS=who | wc -l
echo -e “Logged in user are $USERS \n”
UP=date;uptime
echo -e “Uptime is $UP \n”


val=expr 2 + 2
echo “Total value:$val”


a=10
b=20
val=expr $a + $b
echo “a + b :$val”

val=expr $a - $b
echo “a – b :$val”

val=expr $a \* $b
echo “a * b :$val”

val=expr $a / $b
echo “a / b :$val”

val=expr $a % $b
echo “a % b :$val”

if [ $a == $b ]
then
echo ” a is equal to b”
fi

if [ $a != $b ]
then
echo “a is not equal to b”
fi


a=10
b=20
if [ $a -eq $b ]
then
echo “$a -eq $b : a is equal to b”
else
echo “$a -eq $b : a is not equal to b”
fi

if [ $a -ne $b ]
then
echo “$a -ne $b : a is not equal to b”
else
echo “$a -ne $b : a is equal to b”
fi

if [ $a -gt $b ]
then
echo “$a -gt $b : a is less than b”
else
echo “$a -gt $b : a is not less than b”
fi

if [ $a -lt $b ]
then
echo “$a -lt $b :a is less than b”
else
echo “$a -lt $b : a is not less than b”
fi

if [ $a -ge $b ]
then
echo “$a -ge $b : a is greater or equal to b”
else
echo “$a -ge $b : a is not greater or equal to b “
fi

if [ $a -le $b ]
then
echo “$a -le $b : a is less or equal to b”
else
echo “$a -le $b : a is not less or equal to b”
fi


file=”/xxxx.sh”

if [ -r $file ]
then
echo “File has read access”
else
echo “File does not have read access”
fi

if [ -w $file ]
then
echo “File has write permission”
else
echo “File does not have write permission”
fi

if [ -x $file ]
then
echo “File has execute permission”
else
echo “File does not have execute permission”
fi

if [ -f $file ]
then
echo “File is an ordinary file”
else
echo “This is sepcial file”
fi

if [ -d $file ]
then
echo “File is a directory”
else
echo “This is not a direactory”
fi

if [ -s $file ]
then
echo “File size is zero”
else
echo “File size is not zero”
fi

if [ -e $file ]
then
echo “File exists”
else
echo “File does not exist”
fi

val=(a b c d e)
echo ${val[]} echo ${val[@]} len=${#val[]}
echo $len

for item in a b c d e
do
echo $item
done


function Hello(){
echo “Hello world”
}
Hello
echo $?


printf “Hello.shell \n”
printf “%d,%s\n” 1 zhangdl


str=”abcd”
echo ${#str} # 字符串长度

str=”alibaba is a great company”
echo ${str:1:4} # 提取字符串(数字表示字符串中字符对应下标)

string=”alibaba is a great company”
val=expr length $string
echo $val

Share this:

码字很辛苦,转载请注明来自技术联盟《shell 脚本Demo》

评论