3 个实例介绍 shell 脚本中几个特殊参数的用法

系统 Linux
在本文中讨论的一些shell特殊参数是:$*,$@,$#,$$,$!

[[402692]]

在本文中讨论的一些shell特殊参数是:$*,$@,$#,$$,$!

示例1:使用 $*和$@ 来扩展位置参数

本实例脚本中使用$*和$@参数: 

  1. [root@localhost scripts]# vim expan.sh  
  2. #!/bin/bash  
  3. export IFS='-'  
  4. cnt=1  
  5. # Printing the data available in $*  
  6. echo "Values of \"\$*\":"  
  7. for arg in "$*"  
  8. do  
  9.   echo "Arg #$cnt= $arg"  
  10.   let "cnt+=1"  
  11. done  
  12. cnt=1  
  13. # Printing the data available in $@  
  14. echo "Values of \"\$@\":"  
  15. for arg in "$@"  
  16. do  
  17.   echo "Arg #$cnt= $arg"  
  18.   let "cnt+=1"  
  19. done 

下面是运行结果: 

  1. [root@localhost scripts]# ./expan.sh "Hello world" 2 3 4  
  2. Values of "$*":  
  3. Arg #1Hello world-2-3-4  
  4. Values of "$@":  
  5. Arg #1Hello world  
  6. Arg #22= 2  
  7. Arg #33= 3  
  8. Arg #44= 4 

export IFS='-'表示使用" - "表示内部字段分隔符。

当打印参数$*的每个值时,它只给出一个值,即是IFS分隔的整个位置参数。

而$@将每个参数作为单独的值提供。

示例2:使用$#统计位置参数的数量

$#是特殊参数,它可以提更脚本的位置参数的数量: 

  1. [root@localhost scripts]# vim count.sh  
  2. #!/bin/bash  
  3. if [ $# -lt 2 ]  
  4. then  
  5.   echo "Usage: $0 arg1 arg2"  
  6.   exit  
  7. fi  
  8. echo -e  "\$1=$1"  
  9. echo -e "\$2=$2"  
  10. let add=$1+$2  
  11. let sub=$1-$2  
  12. let mul=$1*$2  
  13. let div=$1/$2  
  14. echo -e "Addition=$add\nSubtraction=$sub\nMultiplication=$mul\nDivision=$div\n" 

下面是运行结果: 

  1. [root@localhost scripts]# ./count.sh   
  2. Usage: ./count.sh arg1 arg2  
  3. [root@localhost scripts]# ./count.sh 2314 15241  
  4. $1=2314  
  5. $2=15241  
  6. Addition=17555  
  7. Subtraction=-12927  
  8. Multiplication=35267674  
  9. Division=0 

脚本中if [ $# -lt 2 ]表示如果位置参数的数量小于2,则会提示"Usage: ./count.sh arg1 arg2"。

示例3:与过程相关的参数 $$和$!

参数$$将给出shell脚本的进程ID。$!提供最近执行的后台进程的ID,下面实例是打印当前脚本的进程ID和最后一次执行后台进程的ID: 

  1. [root@localhost scripts]# vim proc.sh  
  2. #!/bin/bash  
  3. echo -e "Process ID=$$"  
  4. sleep 1000 &  
  5. echo -e "Background Process ID=$!" 

下面是执行的结果: 

  1. [root@localhost scripts]# ./proc.sh   
  2. Process ID=14625  
  3. Background Process ID=14626  
  4. [root@localhost scripts]# ps  
  5.    PID TTY          TIME CMD  
  6.   3665 pts/0    00:00:00 bash  
  7.  14626 pts/0    00:00:00 sleep  
  8.  14627 pts/0    00:00:00 ps 

 

 

责任编辑:庞桂玉 来源: 良许Linux
相关推荐

2019-08-09 13:50:08

shellLinux

2021-05-11 07:50:31

BashShell脚本

2019-08-02 09:13:22

Linux脚本语言欢聚时代

2021-05-12 10:17:15

Shell工具Linux

2019-08-13 11:53:01

脚本语言AWKBash

2021-04-15 11:21:26

Shell脚本Linux

2019-10-31 08:22:39

shell脚本Linux

2021-04-11 07:56:42

ShellLinux

2023-11-13 22:08:05

ShellLinux

2010-11-24 15:53:11

MySQL中SELEC

2010-07-01 14:25:31

UML时序图

2021-06-07 13:02:31

Shell脚本Linux

2022-07-21 14:38:17

PythonShell

2010-09-10 13:25:22

2017-03-08 11:10:39

LinuxShell命令

2019-08-12 07:45:44

Linux脚本shell

2010-03-26 15:28:05

Python编写

2021-05-06 15:18:09

Shell脚本Linux

2018-08-28 16:02:59

LinuxShellBash

2020-10-27 07:51:12

Shell脚本日期
点赞
收藏

51CTO技术栈公众号