bash语法

if 判断语句

var=$1
if [ $var -eq 1 ]; then
    echo 'var is 1'
elif [ $var -eq 2 ]; then
    echo 'var is 2'
else
    echo 'var is not 1 and 2'
fi

# case 选择语句, 即我们一般语法中的switch
case $var in
    'value1')
        echo -e 'var is value1 for first place'
    ;;

    'value2')
        echo -e 'var is value2 for second place'
    ;;

    *)
        echo -e 'var is eq value1 or value2, so this is a default ouptput'
    ;;
esac

for 循环语句

  • case 1 输入数字
for i in 1 2 3 4 5 6
do 
    echo -e "current value is $i"
done
  • case 2 输出字符串
for i in 'this is a string , will be output one by one'
do 
    echo $i
done
  • case 3 输出文件夹
for file in $HOME/.*
do
    echo $file
done
  • case 4 输出数组
for ele in (1,2,3,4,hello)
do
    echo $ele
done
  • case 5 遍历文件夹
for file in <path>
do
    if test -f $file;then
       rm $file
    else
        echo "$file is a dir"
    fi
done