初学简单shell script,实践即可懂!
1,带参数输入
echo "The name of the script is :"$0
echo "the first parameter is:"$1
执行
chmod +x 1_echo.sh
bash 1_echo.sh hello
结果
The name of the script is :1_echo.sh
the first parameter is:hello
2,判断文件是否存在
file=$1
if [ -f $file ]
then
echo -e "The $file exist!"
else
echo -e "The $file does not exist!"
fi
3,相加
echo "Please enter the first number:"
read input1
echo "Please enter the second number:"
read input2
echo "The first number add the second number is:" $((input1 + input2))
执行
chmod +x 3_add.sh
bash 3_add.sh
结果
Please enter the first number:
4
Please enter the second number:
4
The first number add the second number is: 8
4,比较
echo "------------start--------------"
echo "Please input the first number :"
read input1
echo "Please input the second number:"
read input2
if [ $input1 -eq $input2 ]
then
echo "input1 equal to input2"
elif [ $input1 -gt $input2 ]
then
echo "input1 is greater than input2"
else
echo "input1 is smaller then input2"
fi
echo "-------------end-------------"
执行
chmod +x 4_compare.sh
bash 4_compare.sh
结果
------------start--------------
Please input the first number :
1
Please input the second number:
4
input1 is smaller then input2
-------------end-------------
5 ip
echo "Please enter a IP adress"
read ip
if [ ! -z $ip ]
then
ping -c 1 $ip
if [ $? -eq 0 ]
then
echo "Machine is giving ping response"
else
echo "Machine is not pinging"
fi
else
echo "IP Address is empty"
fi
执行
chmod +x 5_ip.sh
bash 5_ip.sh
结果
Please enter a IP adress
210.72.131.130
PING 210.72.131.130 (210.72.131.130) 56(84) bytes of data.
64 bytes from 210.72.131.130: icmp_seq=1 ttl=62 time=4.64 ms
--- 210.72.131.130 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 4.645/4.645/4.645/0.000 ms
Machine is giving ping response
6,string length
echo "please enter a string:"
read str
length=${#str}
echo the length is : $length
执行
chmod +x 6_str_len.sh
bash 6_str_len.sh
结果
please enter a string:
string
the length is : 6
7, while
echo "enter a absolute path of a file name"
read filename
exec <$filename
while read line
do
echo $line
done
number=0
while [ $number -lt 10 ]
do
echo "number = $number"
number=$((number+1))
done
执行
chmod +x 7_print.sh
bash 7_print.sh
结果
enter a absolute path of a file name
/etc/profile
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
......
number = 0
number = 1
number = 2
number = 3
number = 4
number = 5
number = 6
number = 7
number = 8
number = 9