SHELL入门学习

本文介绍了Shell脚本的基础知识,包括变量的使用,如字符串长度计算;echo命令的实践,展示如何读取输入及重定向输出;printf命令的格式化输出;test命令进行条件判断的示例;if-then语句的运用;while循环的实现;以及如何定义和调用Shell函数。通过这些基础,读者可以快速上手Shell脚本编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SHELL 入门学习

shell 变量

vim shellViable.sh

#! /bin/bash
# shell demo
string="abcd"
echo ${#string}
echo $string

echo "Sheel "
echo "$0"
echo "$1"
echo "$2"
echo "$3"

val=`expr 2 + 2`
echo "number sum:$val"
[root@alliyun cainiaoSheelScript]# chmod +x  shellViable.sh
[root@alliyun cainiaoSheelScript]# ./shellViable.sh 
4
abcd
Sheel 
./shellViable.sh



number sum:4

shell echo

vim shellEcho.sh

#! /bin/bash
# echo 
echo "It is a test"
echo It is a test

read name
echo $name It is a test

echo It is a test >myfile
[root@alliyun cainiaoSheelScript]# chmod +x shellEcho.sh
[root@alliyun cainiaoSheelScript]# ./shellEcho.sh 
It is a test
It is a test
look
look It is a test

shell printf

vim shellPrintf.sh

#! /bin/bash
# printf
echo Hello,sheel
printf Hello,sheel "\n"

printf "%-10s %-8s %-4s \n"
printf "%-10s %-8s %-4.2f \n"
printf "%-10s %-8s %-4.2f \n"
printf "%-10s %-8s %-4.2f \n"
[root@alliyun cainiaoSheelScript]# chmod +x shellPrintf.sh 
[root@alliyun cainiaoSheelScript]# ./shellPrintf.sh 
Hello,sheel
Hello,sheel                         
                    0.00 
                    0.00 
                    0.00 

shell test

vim shellTest.sh

#! /bin/bash
# sheel test
num1=100
num2=101
if test $num1 -eq $num2
then
        echo true
else
        echo false
fi

[root@alliyun cainiaoSheelScript]# chmod +x shellTest.sh
[root@alliyun cainiaoSheelScript]# ./shellTest.sh 
false

shell if then

vim shellIfThen.sh

#! /bin/bash
# if then else then

num1=100
num2=200

if [ $num1 -eq 100 ]
then
        echo num1 is 100
else
        echo num1 is not 100
fi

if  [ $num2 -eq 100 ]
then
        echo num2 is 100
elif [ $num2 -eq 200 ]
then
        echo num2 is 200
else
        echo num2 is not 200
fi
~        
[root@alliyun cainiaoSheelScript]# chmod +x shellIfThen.sh 
[root@alliyun cainiaoSheelScript]# ./shellIfThen.sh 
num1 is 100
num2 is 200

shell While

vim shellWhile.sh

#! /bin/bash
# sheel while

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

[root@alliyun cainiaoSheelScript]# chmod +x shellWhile.sh 
[root@alliyun cainiaoSheelScript]# ./shellWhile.sh 
1
2
3
4
5

shell function

vim shellFunction.sh

#! /bin/bash
# function
domoFun(){
        echo this is my first sheel fun!
}

echo fun start..
domoFun
echo fun end...

[root@alliyun cainiaoSheelScript]# chmod +x shellFunction.sh 
[root@alliyun cainiaoSheelScript]# ./shellFunction.sh 
fun start..
this is my first sheel fun!
fun end...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

one 大白(●—●)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值