码迷,mamicode.com
首页 > 系统相关 > 详细

shell 入门例子

时间:2015-07-27 14:50:29      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

for循环
     for loop in 1 2 3 4 5
do
     echo "The value is: $loop"     (双引号和无引号均可以,单引号不行,输出$loop)
done
 
 
运行结果:

The value is: 1

The value is: 2

The value is: 3

The value is: 4

The value is: 5
 
 
 
http://www.cnblogs.com/dwdxdy/archive/2012/07/25/2608816.html  shell 逐行读入文本
 
 
算术比较:
-gt 大于
-lt 小于
-eq 等于
-ne 不等于
-ge 大于或等于
-le  小于或等于
 
 
 
 
-f file 检测文件是否是普通文件(既不是目录,也不是设备文件),如果是,则返回 true。
-d file     检测文件是否是目录,如果是,则返回 true。
-r file     检测文件是否可读,如果是,则返回 true。
-w file     检测文件是否可写,如果是,则返回 true。
-x file     检测文件是否可执行,如果是,则返回 true。
 
 
if 语句三种格式
if....fi
if...else...fi
if...elif...else...fi
 
 
 
#!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
    echo "a is equal to b"
elif [ $a -gt $b ]
then
    echo "a is greater than b"
elif [ $a -lt $b ]
then
    echo "a is less than b"
else
    echo "None of the condition met"
fi
运行结果:
a is less than b
 
 
 
 
#!/bin/bash
for file in `ls`
do
    echo $file
done
 
``里面可以执行终端命令
 
 
 
 
 
示例

#!/bin/bash
counter=0
while [ $counter -lt 5 ]
do
    ((counter++))
    echo "counter is $counter"
done

结果:
counter is 1
counter is 2
counter is 3
counter is 4
counter is 5
 
或这样也可a=`expr $a + 1` #加号两边有空格
 
 
 
 
 
 
流程控制:
#!/bin/bash
while :
do
    echo -n "Input a number between 1 to 5:"
    read aNum
    if [ "$aNum" -ge 1 ] && [ "$aNum" -le 5 ]
    then
        echo "GOOD BOY!"
    
    else
        echo "BAD MAN! BYE!"
        break;
    fi
done
 
 
 
函数:
#!/bin/bash
Hello () {
    echo "Url is http://qunar.it"
}
#调用函数
Hello

结果:
Url is http://qunar.it
 
 
 
 
 
 
特殊变量:
1.$1,$2,$3...${10},${11}...表示第1个参数,第二个参数...
2.$# 表示参数个数
3.$* 传递给脚本或函数的所有参数。
4.$@ 传递给脚本或函数的所有参数。
5.$? 函数返回值
 
#!/bin/bash
funWithParam(){
    echo "The value of the first parameter is $1 !"
    echo "The value of the second parameter is $2 !"
    echo "The value of the tenth parameter is $10 !"
    echo "The value of the tenth parameter is ${10} !"
    echo "The value of the eleventh parameter is ${11} !"
    echo "The amount of the parameters is $# !" # 参数个数
    echo "The string of the parameters is $* !" # 传递给函数的所有参数

echo "The string of the parameters is $@ !" # 传递给函数的所有参数Test

    return 11 #返回值
echo "The result value is $? !" # 传递给函数的fan huiZhi
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
echo "The return value is $?"
 
 
 
 
 
还是linux下的shell编程。

    var1=/usr/lib/abcdefg.so.bak  
    var2=/usr/sbin/ifconfiggg  
    all_name=`basename $var1`  
    sub_name1=`basename $var1 .bak`  
    sub_name2=`basename $var2 gg`  
      
    echo "all_name: $all_name"      #all_name: abcdefg.so.bak  
    echo "sub_name1: $sub_name1"    #sub_name1: abcdefg.so  
    echo "sub_name2: $sub_name2"    #sub_name2: ifconfig  


是的,主要是使用命令 basename解析带路径的文件名称

shell 入门例子

标签:

原文地址:http://www.cnblogs.com/balfish/p/4679863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!