前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Shell编程自动化之特殊变量、特殊状态变量和Shell子串

Shell编程自动化之特殊变量、特殊状态变量和Shell子串

原创
作者头像
星如雨落
发布2024-01-12 21:32:09
1810
发布2024-01-12 21:32:09
举报
文章被收录于专栏:shell自动化
一、特殊变量
代码语言:bash
复制
$0   获取shell脚本文件名,以及脚本路径
$n   获取shell脚本的第n个参数,n在1~9之间,如:$1,$2,大于9则需要写${10},参数用空格隔开。
$#   获取执行的shell脚本后面的参数总个数
$*   获取shell脚本所有的参数,不加引号等同于$@作用,加上引号"$*"作用是接收所有参数为单个字符串,"$1 $2..."
$@   不加引号,效果同上,加引号,是接收所有参数为独立字符串,如"$1" "$2" "$3" ...,空格保留

实例1:

代码语言:bash
复制
test@VM-4-16-debian:~/shell$ cat test.sh
#!/bin/bash

echo "hello word"

echo "脚本文件名:$0"
echo "第一个参数: $1"
echo "第三个参数: $3"
echo "参数总个数: $#"

test@VM-4-16-debian:~/shell$ chmod 755 test.sh 

test@VM-4-16-debian:~/shell$ ./test.sh gao 10 20 30
hello word
脚本文件名:./test.sh
第一个参数: gao
第三个参数: 20
参数总个数: 4

实例2:

代码语言:bash
复制
test@VM-4-16-debian:~/shell$ cat test1.sh 
#!/bin/bash

for var in "$*"
do 
        echo "$var"
done

echo "---------"

for var in "$@"
do 
        echo "$var"
done

test@VM-4-16-debian:~/shell$ chmod 755 test1.sh 

test@VM-4-16-debian:~/shell$ ./test1.sh ceshi 10 20 30
ceshi 10 20 30
---------
ceshi
10
20
30
二、特殊状态变量
代码语言:bash
复制
$?   上一次命令执行状态返回值,0正确,非0失败
$$   当前shell脚本的进程号PID
$!   上一次后台进程的PID
$_   再次之前执行的命令,最后一个参数
三、shell子串用法

bash基础内置命令

代码语言:bash
复制
echo   -n 不换行输出
       -e 解析字符串中的特殊符号
       \n 换行
       \r 回车
       \t 制表符 四个空格
       \b 退格
eval    执行多个命令
exec    不创建子进程,执行后续命令,且执行完毕后,自动exit

shell子串用法

代码语言:bash
复制
${变量}                            返回变量值
${#变量}                           返回变量长度、字符长度
${变量:start}                      返回变量start数值之后的字符
${变量:start:length}              提取变量start之后的length限制的字符
${变量#word}                        从变量开头删除最短匹配的word字符串
${变量##word}                        从变量开头删除最长匹配的word字符串
${变量%word}                        从变量结尾删除最短匹配的word字符串
${变量%%word}                        从变量结尾删除最长匹配的word字符串
${变量/pattern/string}            用string代替第一个匹配的pattern
${变量//pattern/string}            用string代替所有匹配的pattern

实例1:

代码语言:bash
复制
test@VM-4-16-debian:~/shell$ temp="helloworld"
test@VM-4-16-debian:~/shell$ echo ${temp}
helloworld
test@VM-4-16-debian:~/shell$ echo ${#temp}
10
test@VM-4-16-debian:~/shell$ echo ${temp:2}
lloworld
test@VM-4-16-debian:~/shell$ echo ${temp:2:5}
llowo

实例2:

代码语言:bash
复制
test@VM-4-16-debian:~/shell$ string=abc12342341
test@VM-4-16-debian:~/shell$ echo ${string#a*3}
42341
test@VM-4-16-debian:~/shell$ echo ${string#ab}
c12342341
test@VM-4-16-debian:~/shell$ echo ${string##a*3}
41
test@VM-4-16-debian:~/shell$ echo ${string%3*1} 
abc12342
test@VM-4-16-debian:~/shell$ echo ${string%%3*1}
abc12
test@VM-4-16-debian:~/shell$ echo ${string/34/hell}
abc12hell2341
test@VM-4-16-debian:~/shell$ echo ${string//34/hell}
abc12hell2hell1

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、特殊变量
  • 二、特殊状态变量
  • 三、shell子串用法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档