shell基本语法练习

来源:互联网 发布:英文域名注册 编辑:程序博客网 时间:2024/05/16 01:42

自己在ubuntu 14.04上面试了一些

#!/bin/bash
num=20
num1=30
num2=35
num3=90
str1=jack
str2=pony
path=/usr/bin




if [ -d /usr/bin ]
then
echo pppppppath
else
echo noppppppath
fi


:<<!
#调用函数
source func.sh  
func


#func.sh为一个文件,里面写了一个函数,内容如下:
#!/bin/bash
function func()
{
    echo this is a function
}

if [ $num1 -lt $num2 -a $num2 -gt $num3 ] #-a 与 -o 或 ! 非
then
echo "11111111"
else
echo "222222222"
fi
#或
if [[ $num1 -lt $num2 && $num2 -gt $num3 ]] #&& ||
then
echo "&&&&&&&&&"
else
echo "|||||||||"
fi




#case使用
case $num in
        1)
            echo 1
                ;;
        2)
            echo 2
                ;;
        10)
            echo 10
                ;;
        *)
            echo something else
                ;;               
esac

while [ $num -lt 10 ]
do
    echo $num
    let num++  #要用bash运行,否则会报let not found,因为默认shell为dash
done


if [ $num -lt $num2 ]
then
echo num2 is large than num
else
echo num2 is less than num
fi


if [ -z $str1 ]
then
echo str1 is empty
else
echo str1 is not empty
fi
!




#for i in 1 2 3 4 5 6 7 8 9 
#do
#    echo $num
#done


for i in {0..9}  
do  
  echo 111111111  
done 


for ((i=0;i<10;i++))  
do  
  echo $num 
done 


#echo "this is the ${num}nd"


#echo $PATH


:<<!


文件比较运算符
-e filename  如果 filename存在,则为真  [ -e /var/log/syslog ]
-d filename  如果 filename为目录,则为真  [ -d /tmp/mydir ]
-f filename  如果 filename为常规文件,则为真  [ -f /usr/bin/grep ]
-L filename  如果 filename为符号链接,则为真  [ -L /usr/bin/grep ]
-r filename  如果 filename可读,则为真  [ -r /var/log/syslog ]
-w filename  如果 filename可写,则为真  [ -w /var/mytmp.txt ]
-x filename  如果 filename可执行,则为真  [ -L /usr/bin/grep ]
filename1-nt filename2  如果 filename1比 filename2新,则为真  [ /tmp/install/etc/services -nt /etc/services ]
filename1-ot filename2  如果 filename1比 filename2旧,则为真  [ /boot/bzImage -ot arch/i386/boot/bzImage ]
字符串比较运算符 (请注意引号的使用,这是防止空格扰乱代码的好方法)
-z string  如果 string长度为零,则为真  [ -z "$myvar" ]
-n string  如果 string长度非零,则为真  [ -n "$myvar" ]
string1= string2  如果 string1与 string2相同,则为真  [ "$myvar" = "one two three" ]
string1!= string2  如果 string1与 string2不同,则为真  [ "$myvar" != "one two three" ]
算术比较运算符
num1-eq num2  等于 [ 3 -eq $mynum ]
num1-ne num2  不等于 [ 3 -ne $mynum ]
num1-lt num2  小于 [ 3 -lt $mynum ]
num1-le num2  小于或等于 [ 3 -le $mynum ]
num1-gt num2  大于 [ 3 -gt $mynum ]
num1-ge num2  大于或等于 [ 3 -ge $mynum ]

!

读写输入一个值,字符串,数组等操作参考下面链接:


参考链接:http://blog.csdn.net/u011204847/article/details/51184883



原创粉丝点击