shell学习

本文详细介绍了Shell脚本的基础知识,包括shell概述、变量、运算符、条件判断、流程控制、读取控制台输入、函数、综合应用、正则表达式以及文本处理工具的使用。通过实例讲解了如何编写和运用Shell脚本,帮助读者掌握Linux环境下的自动化任务处理。

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


一、shell概述

[root@localhost ~]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash
/bin/tcsh
/bin/csh

一个简单的入门

[root@localhost ~]# ls
aa               Hello.java                                original-ks.cfg
anaconda-ks.cfg  mysql-community-release-el7-5.noarch.rpm
[root@localhost ~]# mkdir shell
[root@localhost ~]# cd shell/
[root@localhost shell]# touch hello.sh
[root@localhost shell]# vim hello.sh
[root@localhost shell]# ls
hello.sh
[root@localhost shell]# bash hello.sh
helloworld

补:hello.sh里面的内容
在这里插入图片描述
注意权限

[root@localhost shell]# ./hello.sh
-bash: ./hello.sh: 权限不够
[root@localhost shell]# chmod +x ./hello.sh
[root@localhost shell]# ll 
总用量 4
-rwxr-xr-x. 1 root root 31 7月  14 04:01 hello.sh
[root@localhost shell]# ./hello.sh
helloworld

./相对路径比较常用
其他执行方法

[root@localhost shell]# source hello.sh
helloworld
[root@localhost shell]# source /root/shell/hello.sh
helloworld
[root@localhost shell]# . hello.sh
helloworld
[root@localhost shell]# type source
source 是 shell 内嵌

二、变量

全局变量
局部变量
局部变量只对自己有效对外面的没有效
env:查看所有的环境变量

  • 自定义变量
    等号左右不能有空格
    有空格加引号
[root@localhost shell]# a=2
[root@localhost shell]# echo $2

[root@localhost shell]# echo $a
2
[root@localhost shell]# my_1=hello
[root@localhost shell]# echo $my_1
hello

定义只读

readonly b=5

撤销

unset 要撤销的文件
只读的变量不能撤销

局部变量提升为全局变量

export 变量名
  • 特殊变量
    $n:1-9代表参数,10以上用{10},$0代表脚本本身名称。
    $#:获取输入参数的个数
    $*:所有参数,把参数看作一个整体
    $@:所有参数,把参数区分对待

parameter里的内容:

#!/bin/bash
echo '====$n===='
echo script name:$0
echo 1st parameter :$1
echo 2nd parameter :$2
echo '====$#===='
echo parameter numbers:$#
echo '====$*===='
echo $*
echo '====$@===='
echo $@
[root@localhost shell]# /root/shell/parameter abc def
====$n====
script name:/root/shell/parameter
1st parameter :abc
2nd parameter :def
====$#====
parameter numbers:2
====$*====
abc def
====$&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值