当前位置:首页 > 编程笔记 > 正文
已解决

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

来自网友在路上 174874提问 提问时间:2023-09-25 02:10:43阅读次数: 74

最佳答案 问答题库748位专家为你答疑解惑

一、特殊变量
$0   获取shell脚本文件名,以及脚本路径
$n   获取shell脚本的第n个参数,n在1~9之间,如:$1,$2,大于9则需要写${10},参数用空格隔开。
$#   获取执行的shell脚本后面的参数总个数
$*   获取shell脚本所有的参数,不加引号等同于$@作用,加上引号"$*"作用是接收所有参数为单个字符串,"$1 $2..."
$@   不加引号,效果同上,加引号,是接收所有参数为独立字符串,如"$1" "$2" "$3" ...,空格保留

实例1:

test@VM-4-16-debian:~/shell$ cat test.sh
#!/bin/bashecho "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:

test@VM-4-16-debian:~/shell$ cat test1.sh 
#!/bin/bashfor var in "$*"
do echo "$var"
doneecho "---------"for var in "$@"
do echo "$var"
donetest@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
二、特殊状态变量
$?   上一次命令执行状态返回值,0正确,非0失败
$$   当前shell脚本的进程号PID
$!   上一次后台进程的PID
$_   再次之前执行的命令,最后一个参数
三、shell子串用法

bash基础内置命令

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

shell子串用法

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

实例1:

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:

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

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Shell编程自动化之特殊变量、特殊状态变量和Shell子串":http://eshow365.cn/6-13156-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!