shell脚本!!!开始学习啦~~~~

本文介绍Shell脚本的基础知识,包括变量使用、条件判断、循环结构、数组操作及文件测试等核心概念。通过实例演示如何编写简单的Shell脚本来实现特定功能。

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

shell脚本就是通过一些相关shell命令的组合来达到完成一个任务的文件,文件一般是以,sh结尾。

下面的代码复制都能直接运行!!!!!! 最好自己照着敲一遍~~~

以下是 test.sh 文件

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash


echo "hello my shell script"   #用井号后面内容(#)来表示备注


echo $BASH     #变量有系统变量和用户变量,在shell脚本中,经常用到系统变量。我们用$变量名称来引用变量。

echo $PATH

name=zhq     #自定义变量  赋值不能有空格!!!!!!!

echo MY name is $name

echo Yours name is?

read -p "Please input " youname1 youname2 youname3   # 输入时逗号隔开

 #用户输入  -p是promote,提示的意思,就是可以让用户在提示语相同一行输入内容。

echo "hello $youname1 $youname2 $youname3"

read -p "Please input a name:" user_name
read -sp "Please input a passwrod" pass_word   # -sp  输入过程中看不见
echo "you inpur name is "$user_name 

echo "you inpur pswd is "$pass_word

-------------------------------------------------------------------------------------------------------------------------------------------------------

yixiatest2.sh

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash

#how to pass arguments to shell sctript

echo $0 $1 $2 #it equal print the arugments you had  give
#终端返回结果  ./demo.sh 312,3123,12

#上面可以看到$0表示 我们运行sh文件的语句 ./demo.sh,这个不是一个我们提供的真实的参数。

#换成args数组方式去存储参数列表
args=("$@")
echo ${args[0]}  ${args[1]}  ${args[2]}  ${args[3]}  
#终端返回结果  312,3123,12

#更加简洁的写法
echo $@     
#$@可以表示传入参数列表,直接打印出来。

echo $#  

#$#可以存储参数的个数值。

-------------------------------------------------------------------------------------------------------------------------------------------------------

以下是test3.sh

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash
#this  is an example of a if -than


score=91
#if-then
#固定格式!!!!
if(("$score">90))
then
echo "well Done"
fi

word="abc"
#if-then else
if [ $word = "abcc" ] #必须空格!!!!!!需要注意什么时候是小括号什么是中括号 ,什么时候是两个小括号
then
echo "true" #可以顶到写 不过为了美观~~
else
echo "false"
fi


#if-then elif-then else
num=7
if (( $num > 7 )) 
then
echo " $num is bigger "
elif (( $num < 7 ))
then
echo " 7 is bigger "
else
echo " there are equal "
fi



#整数比较符号
if [ 1 -eq 1 ]
then
echo "[equal to]"
fi


if [ 1 -ne -1 ]
then
echo "[not equal to]"
fi


if [ 1 -gt 0 ]
then
echo "[greater to 大于]"
fi


if [ 1 -ge 1 ]
then 
echo "[greater than or equal to 大于或等于]"
fi


if [ 1 -lt 2 ]
then
echo "[less than]"
fi


if [ 1 -le 2 ] 
then
echo "[less than or equal to]"
fi


if (( -1 < 0 ))
then
echo "((<))"
fi


if (( 1 <= 1 ))
then
echo "((<=))"
fi


if (( 1 > 0 ))
then
echo "((>))"
fi


if (( 1 >= 1 ))
then
echo "((>=))"
fi


 #此写法不行 因为会被认为是在赋值,所以用(())不行
 #if (( 1 = 1))
 #then 
 #echo "((=))"
 #fi

 #意外的发现以下写法都可以!!!!!!!!
if (( 1 == 1))
then 
echo "((==))"
fi

if [ 1 == 1 ]
then 
echo "[==]"
fi

if [ 1 = 1 ]
then 
echo "[=]"
fi

if [[ 1 == 1 ]]
then 
echo "[[==]]"
fi

if [[ 1 = 1 ]]
then 
echo "[[=]]"
fi

 # 整数比较总结一下
 # 1. 用字母比较大小的必须用"[]"。
 # 2. 用字符比较大小必须要用"(())"。
 # 3. 特别需要注意的是比较等于的时候必须用 "==" ,如果非要用 "=" 就用"[]"。
 # 4.  另外最好都空格!除了赋值不能空格,还有一些情况也不能有空格,下面会出现。


 #字符串比较
if [[ "abc" = "abc" ]]
then 
echo "[[=]]"
fi

if [[ "abc" == "abc" ]]
then 
echo "[[==]]"
fi

if [[ "ab" != "abc" ]]
then 
echo "[[!=]]"
fi

if [[ "abc" > "ab" ]]
then 
echo "[[>]]"
fi

if [[ "ab" < "abc" ]]
then 
echo "[[<]]"
fi

# 字符串总结
# 1. 没啥好总结的。。。全部都用双中括号。。。
# 2. 在啰嗦一句吧,,,字符串比较没有大于等于 等等这些操作。

-------------------------------------------------------------------------------------------------------------------------------------------------------

以下是test.sh

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash

# file test operators


echo -e  "Enter the name of file: \c"
read filename  #输入test 此文件真的不存在
if [ -e $filename ]  #e 表示文件是否存在。
then
echo "File found"
else
echo "File is not exist or not found" #输出此
fi
         #mkdir test 创建文件夹之后再执行 输出 File found


if [ -s $filename ]  # s 检查文件是否为空
then
echo " $filename is not empty "
else
echo "$filename is empty" 
fi


if [ -d $filename ]  # d 判断是否是一个目录
then
echo " $filename is a directory "
else
echo " $filename is not a directory" 
fi


if [ -f $filename ]  # -f表示file,判断是否是常规的文件
then
echo " $filename is a file "
else
echo " $filename is not a file" 
fi

-------------------------------------------------------------------------------------------------------------------------------------------------------

以下为新的 .sh

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash

   #我们来实现一个简单的脚本,这个脚本的功能是:先判断文件是否是常规文件,如果存在,继续判断文件是否有写的权限,如果有写的权限,然后需要接受键盘的输入,并把输入的字符保存到文件的尾部,不能覆盖原来文件的内容。如果文件没有权限,提示没有写入权限。


echo -e "Enter the name  of file: \c"
read filename

if [ -e $filename ]
then
if [ -w $filename ]  #判断是否有写入权限
then
echo "type some text data. press ctrl+d to quit"
cat >> $filename 
  else
echo " $filename do not have write permissions"

fi
else
echo "$filename is not exist"
fi

-------------------------------------------------------------------------------------------------------------------------------------------------------

同上

------------------------------------------------------------------------------------------------------------------------------------------------------ 

#   &&  逻辑与的多种写法
age=25


if  [ $age -gt 18 ] && [ $age -lt 30 ] 
then 
echo "valid age"
else
echo "not valid age"
fi

age=30
if [ $age -gt 18 -a  $age -lt 30 ] 
then
echo "valid age"
else
echo "not valid age"
fi


if [[ $age -gt 18 && $age -lt 30 ]]
then 
echo "valid age"
else 
echo "not valid age"
fi



  #   &&  逻辑或的多种写法
age=1

if  [ $age -gt 18 ] || [ $age -lt 30 ] 
then 
echo "valid age"
else
echo "not valid age"
fi


if  [[ $age -gt 18 || $age -lt 30 ]]
then 
echo "valid age"
else 
echo "not valid age"
fi

-------------------------------------------------------------------------------------------------------------------------------------------------------

同上

-------------------------------------------------------------------------------------------------------------------------------------------------------

 #数学基本运算


echo 3+5


num1=5
num2=1


#echo $(num1 + num2 ) 这样是不行的 说明运算必须要双括号
echo $(( $num1 + $num2 )) # 3+5
echo $((num1 + num2 )) 
echo $(( num1 - num2 ))
echo $(( num1 * num2 )) 
echo $(( num1 / num2 ))
echo $(( num1 % num2 ))


#做运算不用写$  写了就不会做运算!!


echo $( expr $num1 + $num2 )
echo $( expr $num1 - $num2 )
echo $( expr $num1 \* $num2 )   #乘法需要转义
echo $( expr $num1 / $num2 )
echo $( expr $num1 % $num2 )


  #bash 不支持 浮点型运算 需要 借助 bc
  #sudo apt-get  install bc
num1=14.5
num2=5


echo "14.5+4"|bc   
 #18.5~~~~

-------------------------------------------------------------------------------------------------------------------------------------------------------

同上

-------------------------------------------------------------------------------------------------------------------------------------------------------

 #case 语句


score=$1


case $score in
"90")
echo "A";;
"80")
echo "B";;
"70")
echo "C";;
"60")
echo "D";;
* )
echo "Default value";;
esac




echo "Please input some charactor "
read value


case $value in 
[a-z])
echo "a-z";;
[A-Z])
echo "A-Z";;
[0-9])
echo "0-9";;
?)
echo "not a-z A-Z 0-9";;
*)
echo "Defalut value";;
esac

-------------------------------------------------------------------------------------------------------------------------------------------------------

同上

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash
 #Shell脚本中的数组的基本使用。数组的遍历,数组的长度,数组的索引查询,数组删除元素,数组添加元素。

os=('linux' 'unix' 'windows' 'Mac')
os[4]='Android'  #add a element
#unset os[1]     #remove
#不能有任何空格!!!!!!
echo "${os[@]}" #全部输出
echo "${os[1]} "    #unix
echo "${!os[@]} "  #输出下标
echo "${#os[@]} "  #输出数组长度



echo -n "Input muliple values into an array:"
read -a array
echo "${array}"
echo "${array[1]}"
echo "${array[@]}" #全部输出
echo "${!array[@]} "
:<<!
Input muliple values into an array:1234
1234

1234
0
Input muliple values into an array:1234
1234

1234

!

 #string is a array object
string=abcdefgh
echo "${string[0]}"  #abcdefgh
echo "${string}"   #abcdefgh
echo "${string[1]}" #     没有就是空的


string[1]=mnopq
echo "${string[1]}"  #mnopq
echo "${string[@]}"
echo "${!string[@]}"  
echo "${#string[@]}"
  #因为都是数组 所以通用

-------------------------------------------------------------------------------------------------------------------------------------------------------

同上

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash 
 # while loops  


n=1  
  
while [ $n -le 10 ]
do  
    echo "$n"
    n=$((n+1))  #这个写法要记忆以下
done 


n=1  
while (( $n <= 10 ))  
do  
    echo "$n"  
    (( n++ ))  #n 可以自增
done


n=1
total=0
while (( $n <= 100 ))
do
total=$(( total + n ))
(( n++ ))
done
echo $total

#加一个sleep


n=1
while (( $n <= 10 ))
do
echo $n
(( n++ ))
sleep 1 #睡眠一秒 
done


  #1秒开一个终端
  #我们先要获取终端的程序名称,例如一般在终端输入firefox就可以启动火狐浏览器,同样的道理,在终端输入终端对应的名称,也可以新开一个终端。
 #点击帮助->关于,得到名称是xfce4-terminal  不过可能是我电脑原因没跑起来~


#n=1  
  
#while (( $n <= 3 ))  
#do  
 #   echo $n  
 #   (( n++ ))  
 #   xfce4-terminal &   
 #   sleep 1  
#done  


  #while循环语句读取文件里面的内容。
 #function one
while read  p
do
echo $p
done < hello.sh


 #function two
cat hello.sh | while read p
do 
echo $p
done  


 #function three
while IFS=' ' read -r line
do
  echo $line
done < hello.sh

-------------------------------------------------------------------------------------------------------------------------------------------------------

同上

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash 
 # until loops  


n=1


until [ $n -ge 10 ]   #为假执行
do
echo "$n"
(( n++ ))
done 


n=1
total=0


until [ $n -ge 101 ]
do
total=$(( total + n ))
(( n++ ))
done
echo $total

-------------------------------------------------------------------------------------------------------------------------------------------------------

同上

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash 
 # until loops  


 #数字循环
for((i=1;i<=10;i++ ))
do
echo $(expr $i \* 3 + 1 );
done


for i in $(seq 1 10)
do
echo $(expr $i \* 3 + 1 )
done


for i in {1..10}
do
echo $(expr $i \* 3 + 1 )
done


awk 'BEGIN{for(i=1; i<=10; i++) print i * 3 +1 }'


 #字符串循环
for i in 'ls'
do
echo $i is file name\!
done


for i in $*  #输入 1,2,3,4,5 
do
echo $i is input chart\!  # 1,2,3,4,5 is input chart!
done


for i in f1 f2 f3
do
echo "$i is appoint"
done


list="rootfs usr data data2"
for i in $list
do
echo $i is appoint
done




 #路径查找
for file in /root/*  #读取目录信息
do
echo $file is file path \!
done


 #/root/Desktop is file path !
 #/root/hello.sh is file path !
 #/root/hello.sh~ is file path !
 #/root/idea.desktop is file path !
 #/root/Navicat is file path !
 #/root/text is file path !




for file in $(ls *.sh)
do
echo $file is file path \!  #hello.sh is file path !
done


#输出.sh结尾的文件名称   


 #for 读文件内容
echo "for line in cat hello.sh"  
SAVEIFS=$IFS  
IFS=$(echo -en "\n")  
for line in $(cat hello.sh)  
do  
  echo  $line;  
done  
IFS=$SAVEIFS  #注意:当文件中有空格或者tab时,一定要设置一下I F S变量。

-------------------------------------------------------------------------------------------------------------------------------------------------------

基本用法就到这了~还是应该结合实际掌握更加熟练,以及理解shell脚本~~ 跟python 有一点点相似~~~

下面就是我自己为了深刻理解自己随便敲得代码 你们也可以看看

就是输入一个文件或目录的加强版  是目录就打印 首层文件名  是文件就是打印文件内容 还判断了文件是否为空是否可写 可写就进行写  是否覆盖文件进行写

-------------------------------------------------------------------------------------------------------------------------------------------------------

#! /bin/bash 
echo "Enter the name of file: \root"
read filename
if [ -e $filename ]
then
if [ -d $filename ]
then
for file in $filename
do
if [ -d $file ]
then
echo "$file is  a dirctory"
for newfile in $file/*
do
if [ -d $newfile ]
then
echo "$newfile is a dirctory"
else
echo "$newfile is a file"
fi
done
fi
done
else
if [ -f $filename ]
then
echo "is a file"
if [ -s $filename ]
then
echo "found,is no empty"
if [ -w $filename ]
then
echo " $filename is a file"
SAVEIFS=$IFS  
IFS=$(echo -en "\n")  #  -n不换行输出 -e处理特殊字符
:<<!
\a 发出警告声;
\b 删除前一个字符;
\c 最后不加上换行符号;
\f 换行但光标仍旧停留在原来的位置;
\n 换行且光标移至行首;
\r 光标移至行首,但不换行;
\t 插入tab;
\v 与\f相同;
\\ 插入\字符;
\nnn 插入nnn(八进制)所代表的ASCII字符;
!




for line in $(cat $filename)  
do  
  echo  $line;  
done  
IFS=$SAVEIFS
echo "$filename type some text data. press ctrl+d to quit"
read -p "if cover file  yes or no" ask  #找了很久的错误,,才发现。我在这里多写了$..导致不能进行比较
if [[ $ask  == "yes" ]]
then
echo "cover file"
cat > $filename
else
cat >> $filename
fi
echo "see file"
SAVEIFS=$IFS  
IFS=$(echo -en "\n")  
for line in $(cat $filename)  
do  
  echo  $line;  
done  
IFS=$SAVEIFS
else
echo "$filename do not have write permissions"
fi
else
echo "is empty"
if [ -w $filename ]
then
echo "type some text data. press ctrl+d to quit"
cat >> $filname
else
echo "$filename do not have write permissions"
fi
fi
else
echo "not is a file"
fi
fi
else
echo "not found"
fi

-------------------------------------------------------------------------------------------------------------------------------------------------------

扩展~~~
read可以带有-a, -d, -e, -n, -p, -r, -t, 和 -s八个选项。

拼接文件  -u

#将afile文件中的前三行与bfile中的前四行拼接在一起

while read -u3 i && read -u4 j;do
echo $i $j
done 3<afile 4<bfile

 输入不在终端显示  -s

read -p "Input passwd:" -s Passwd
echo $Passwd

c限时输入,否则退出  -t

#延迟五秒,没有输入将自动退出
read -p "Input a number:" -t 5 Number

d. 读取限定字符  -n

#从输入中取5个字符
read -p "Input a word:" -n 5 Word

e. 等待输出q退出  

#输入,直到输入q,将自动退出
read -dp -p "Input some words end with q:" word


-a :将内容读入到数值中

echo -n "Input muliple values into an array:"
read -a array
echo "get ${#array[@]} values in array"

-d :表示delimiter,即定界符,一般情况下是以IFS为参数的间隔,但是通过-d,我们可以定义一直读到出现执行的字符位置。例如read –d madfds value,读到有m的字符的时候就不在继续向后读,例如输入为 hello m,有效值为“hello”,请注意m前面的空格等会被删除。这种方式可以输入多个字符串,例如定义“.”作为结符号等等。

-e :只用于互相交互的脚本,它将readline用于收集输入行。读到这几句话不太明白什么意思,先跳过。

-n :用于限定最多可以有多少字符可以作为有效读入。例如echo –n 4 value1 value2,如果我们试图输入12 34,则只有前面有效的12 3,作为输入,实际上在你输入第4个字符‘3’后,就自动结束输入。这里结果是value为12,value2为3。

-p :用于给出提示符,在前面的例子中我们使用了echo –n “…“来给出提示符,可以使用read –p ‘… my promt?’value的方式只需一个语句来表示。

-r :在参数输入中,我们可以使用’/’表示没有输入完,换行继续输入,如果我们需要行最后的’/’作为有效的字符,可以通过-r来进行。此外在输入字符中,我们希望/n这类特殊字符生效,也应采用-r选项。

-s :对于一些特殊的符号,例如箭头号,不将他们在terminal上打印,例如read –s key,我们按光标,在回车之后,如果我们要求显示,即echo,光标向上,如果不使用-s,在输入的时候,输入处显示^[[A,即在terminal上 打印,之后如果要求echo,光标会上移。

-t :用于表示等待输入的时间,单位为秒,等待时间超过,将继续执行后面的脚本,注意不作为null输入,参数将保留原有的值


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值