Shell脚本

224 阅读1分钟

定义变量
declare
#!/bin/bash
#declare.sh
declare -i a=1
declare -i b=2
declare -i c=3
declare -i d=4
echo "the result is --> $a*$b-$c+$d"
declare -i f
f=$a*$b-$c+$d
echo "the result is --> $f"
# define a array
declare -a array=(1 2 3 4 5)
echo ${array[2]}
read
#!/bin/bash
#read.sh
echo 'input two number and press Enter to plus them :'
read num1 num2
echo "fist number is $num1 , second number is $num2"
echo "the result is :" ; expr $num1 + $num2
流程控制
if
#!/bin/bash
#if.sh
echo 'Press y to continue!'
read input
if [ $input = "y" ]
then
echo 'script is running!'
else
echo 'stop!'
fi
#!/bin/bash
#if.sh
echo 'I can say hello to you !'
read input
if [ "$input" = "hello" ]
then 
echo "hello , nice to meet you !"
elif [ -z "$input" ]
then
echo "say something, please !"
else 
echo "I do not know what you say ! but you can say hello to me !"
fi
case
#!/bin/bash
#case.sh
echo 'Please Enter Your Number:'
read number
case "$number" in
1) echo $number is 1 ;;
2) echo $number is 2 ;;
3) echo $number is 3 ;;
*) echo $number is not equals 1 or 2 or 3 ;;
esac
#!/bin/bash
#case.sh
echo 'Enter your choice one|two|three'
read inputStr
case $inputStr in
one) echo 'Your choice is $inputStr' ;;
two) echo 'Your choice is $inputStr' ;;
three) echo 'Your choice is $inputStr' ;;
*) echo 'Usage is [one|two|three]'
esac
for
#!/bin/bash
#for.sh
#Using for to read the user of this linux system.
user=`/bin/cut -d ":" -f1 /etc/passwd | /bin/sort`
echo "The following is your linux system's user:"
for username in $user
do
echo "$username"
done
while
#!/bin/bash
#while.sh
num=0
while [ $num -lt 10 ] ;
do
echo $num
let num+=1
done
#!/bin/bash
#while.sh
sum=0
while [ $sum -lt 4 ]
do
sum=`expr $sum + 1`
/usr/sbin/useradd user$sum
echo '123456' | passwd --stdin user$sum
done
select
#!/bin/bash
#select.sh
PS3='--->'
select cmd in 'ls -l' 'pwd' 'date' 'df -v'
do 
$cmd
break
done
break
#!/bin/bash
#break.sh
while :
do
read cmd
case $cmd in 
[Qq]|[Qq][Uu][Ii][Tt]
break ;;
*) $cmd ;;
esac
done
continue
#!/bin/bash
#continue.sh
for file in 1 exist.txt 3 q.txt
do
if [ ! -f "$file" ]
then
echo "error $file is not a file"
continue
fi
echo "this is $file !!"
done
shift
#!/bin/bash
#shift.sh
until [ $# -eq o ]
do
echo "first param is $1, param num is $#"
shift
done
# bash shift.sh 1 2 3 4
#!/bin/bash
#shift.sh
if [ $# -le 0 ]
then
echo 'Not enough parameters'
exit 1
fi
sum=0
while [ $# -gt 0 ]
do 
sum=`expr $sum + $1`
shift
done
echo $sum
函数
#!/bin/bash
#function.sh
#step one : define a function
#step two : run a function
selfFunction(){
echo 'this is the shell function ! !'
}
selfFunction

Tips
  1. echo $?: 查看上个shell命令的返回状态,0为正确执行,否则为异常状态。