【嵌入式Linux学习】shell脚本入门

  • 一般地,shell脚本必须以#!/bin/bash开头
  • read读取并打印的例子。【注意read读取的变量与引号之间一定要加空格!!!】
#!/bin/bash
read -p "Input your name and age: " name age
echo "Your name is $name, your age is $age"
  • 数值运算时,变量要加两个括号。【#注意等号前后不要加空格!】
#!/bin/bash
echo "Input two int num:"
read -p "first: " first
read -p "second: " second
total=$((first + second))
echo "$first + $second = $total"

  • test判断文件是否存在
#!/bin/bash
echo "Input file name"
read -p "filename " filename
test -e $filename && echo "$filename exist" || echo "$filename not exist"

  • test查看字符串是否一样
#!/bin/bash
echo "Input two string"
read -p "firstStr " firstStr
read -p "secondStr " secondStr
test $firstStr == $secondStr && echo "equal String" || echo "Not equal"
  • []判断符。注意中括号要与里面的内容用空格空开,并且里面的字符串必须加双引号!
o "Input two string"
read -p "firstStr " firstStr
read -p "secondStr " secondStr
[ $firstStr == $secondStr ] && echo "equal String" || echo "Not equal"

  • 默认变量
!/bin/bash
echo "filename:" $0
echo "total param num:" $#
echo "whole param:" $@
echo "first param:" $1
echo "second param:" $2

  • 条件判断。【注意then前面是个分号】
#!/bin/bash

read -p "please input(y/n):" value

if [ "$value" == "Y" ] || [ "$value" == "y" ]; then
    echo "your input is Y"
    exit 0
fi

if [ "$value" == "N" ] || [ "$value" == "n" ]; then
    echo "your input is N"
    exit 0
fi

  • 多个条件判断。【注意结束fi只有一个!】
#!/bin/bash

read -p "please input(y/n):" value

if [ "$value" == "Y" ] || [ "$value" == "y" ]; then
    echo "your input is Y"
    exit 0
elif [ "$value" == "N" ] || [ "$value" == "n" ]; then
    echo "your input is N"
    exit 0
else
    echo "your input can't identify!!!"
fi

  • case语句。【注意最后的通配符不能用引号括起来!】
#!/bin/bash

case $1 in
    "a")
        echo "param is: a"
        ;;
    "b")
        echo "param is: b"
        ;;
    *)
        echo "can't identify!!!"
        ;;
esac

  • 函数调用。【注意函数调用的时候不需要加括号】
#!/bin/bash

function help(){
    echo "this is help cmd"

}
function close(){
    echo "this is close cmd"
}

case $1 in
    "-h")
        help
        ;;
    "-c")
        close
        ;;
esac

  • 函数传参。【注意传参时,同样不需要加括号!!!】
#!/bin/bash

function print(){
    echo "param 1: $1"
    echo "param 2: $2"

}

print a b

  • while循环
in/bash
while [ "$value" != "close" ]
do
    read -p "please input str:" value
done

echo "stop while loop"

  • for循环
#!/bin/bash

for name in zzk zz1 zz2 zz3
do
    echo "your name: $name"
done

  • 常见形式for循环【注意,for是两个括号!!!】
!/bin/bash
read -p "please input count: " count

sum=0
for((i=0; i

你可能感兴趣的:(#,嵌入式Linux基础入门)