Linux初学实战之shell

来源:互联网 发布:esp8266与单片机连接 编辑:程序博客网 时间:2024/05/18 00:26

初学简单shell script,实践即可懂!

1,带参数输入

echo "The name of the script is :"$0echo "the first parameter is:"$1
执行

chmod +x 1_echo.shbash 1_echo.sh hello
结果

The name of the script is :1_echo.shthe first parameter is:hello
2,判断文件是否存在

file=$1if [ -f $file ]thenecho -e "The $file exist!"elseecho -e "The $file does not exist!"fi
3,相加

echo "Please enter the first number:"read input1echo "Please enter the second number:"read input2echo "The first number add the second number is:" $((input1 + input2)) 

执行
chmod +x 3_add.shbash 3_add.sh 
结果

Please enter the first number:4Please enter the second number:4The first number add the second number is: 8
4,比较

echo "------------start--------------"echo "Please input the first number :"read input1echo "Please input the second number:"read input2if [ $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"fiecho "-------------end-------------"
执行

chmod +x 4_compare.shbash 4_compare.sh 
结果

------------start--------------Please input the first number :1Please input the second number:4input1 is smaller then input2-------------end-------------

5 ip

echo "Please enter a IP adress"read ipif [ ! -z $ip ]then        ping -c 1 $ip        if [ $? -eq 0 ]        then                echo "Machine is giving ping response"        else                echo "Machine is not pinging"        fielse        echo "IP Address is empty"fi
执行

chmod +x 5_ip.shbash 5_ip.sh 
结果

Please enter a IP adress210.72.131.130PING 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 0msrtt min/avg/max/mdev = 4.645/4.645/4.645/0.000 msMachine is giving ping response

6,string length

echo "please enter a string:"read strlength=${#str}echo the length is :  $length
执行

chmod +x 6_str_len.sh

bash 6_str_len.sh

结果

please enter a string:stringthe length is : 6
7, while

echo "enter a absolute path of a file name"read filenameexec <$filenamewhile read linedoecho $linedonenumber=0while [ $number -lt 10 ]do        echo "number = $number"        number=$((number+1))done
执行

chmod +x 7_print.shbash 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 = 0number = 1number = 2number = 3number = 4number = 5number = 6number = 7number = 8number = 9

0 0
原创粉丝点击