shell基本用法

#!/bin/bash 

#使用哪个shell执行

echo "hello world"
username="tom"
echo $username

#chmod +x ./test.sh 设置可以执行文件


#for循环输出
for skill in Ada Coffe Action Java; do
    echo "I am good at ${skill}Script"
done
#for file in `ls /etc`; do
#echo "This is name "${file}
#done
#只读变量
readonly username
username="Stevn"
echo $username;
#充值变量
unset username
#截取字符串
string="alibaba is a great company"
echo ${string:4:9}

array_name=(value0 value1 value2 value3)
#数组元素
echo ${array_name[1]}
#全部元素
echo ${array_name[@]}
#数组长度
echo ${#array_name[@]}
echo ${#array_name[*]}
#数组其中一个元素长度
echo ${#array_name[3]}

#参数传递
echo "参数值为:"
echo $1 
echo $2 
echo $# 
echo $* 
echo $$ 
echo $! 
echo $@ 
echo $- 
echo $?
#运算

val=`expr 2 + 2`
echo "两数之和为 : $val"

echo `expr 2-5`
echo `expr 2*5`
echo `expr 2%5`
echo `expr 2/5`
a=2
b=2

if [ $a == $b ]
then
echo "a==b"
else
echo "a!=b"
fi 

if [ $a -eq $b ]
then
echo "1"
else
echo "2" 
fi

echo "this is a test file" >test1.lua
#当前日期
echo `date`

#按照格式打印
printf "%-10s %-8s %-4s
" 姓名 性别 体重kg  
printf "%-10s %-8s %-4.2f
" 郭靖 男 66.1234 
printf "%-10s %-8s %-4.2f
" 杨过 男 48.6543 
printf "%-10s %-8s %-4.2f
" 郭芙 女 47.9876 


#test判断
num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

#文件判断
if test -e ./bash
then
    echo 'The file already exists!'
else
    echo 'The file does not exists!'
fi

#写成一行(适用于终端命令提示符)
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi


for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done


for str in 'This is a string'
do
    echo $str
done


int=1
while(( $int<=5 ))
do
        echo $int
        let "int++"
done


#echo '按下 <CTRL-D> 退出'
#echo -n '输入你最喜欢的电影名: '
#while read FILM
#do
#    echo "是的!$FILM 是一部好电影"
#done


funWithReturn(){
    echo "这个函数会对输入的两个数字进行相加运算..."
    echo "输入第一个数字: "
    read aNum
    echo "输入第二个数字: "
    read anotherNum
    echo "两个数字分别为 $aNum 和 $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "输入的两个数字之和为 $? !"




funWithParam(){
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !"
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73


#包含文件  source filename 或者 . filename
echo "test='1223333'" > ./test1.lua
source ./test1.lua
echo $test

  

原文地址:https://www.cnblogs.com/icyy/p/5280961.html