Shell编程-命令行参数

时间:2020-02-23 14:45:07  来源:igfitidea点击:

在本教程中,我们将学习如何在Shell编程中处理命令行参数。

我们使用命令行参数为shell脚本提供输入。

语法

$sh filename.sh argument1 argument2 ... argumentN

其中: filename.sh是一个shell脚本文件 argument1, argument2... argumentN是参数列表。

例子: $sh greetings.sh Hello World在上面的例子中, greetings.sh是脚本文件。 HelloWorld这些都是论点。

特殊变量

在shell编程中,我们可以使用一些特殊变量来处理命令行参数。

Shell $0变量

它保存脚本的名称。

Shell $1$2... $N变量

这些变量包含提供给脚本的参数。

Shell $#变量

此变量保存传递给脚本的参数总数。

Shell $@$*变量

它们都持有提供给脚本的参数列表。

示例#1:编写一个Shell脚本,将用户数据作为命令行参数,并显示问候语消息

#!/bin/sh
# display the file name
echo "The name of the script file is 
$sh example01.sh 
The name of the script file is example01.sh
Total number of arguments passed to the script = 0
No argument provided to the script.

$sh example01.sh My name is theitroad
The name of the script file is example01.sh
Total number of arguments passed to the script = 5
List of arguments:
My
name
is
theitroad
theitroad
" # display total number of arguments passed to the script echo "Total number of arguments passed to the script = $#" # display all the arguments using for loop if [ $# -gt 0 ] then echo "List of arguments:" for arg in $@ do echo "$arg" done else echo "No argument provided to the script." fi
#!/bin/sh
# function to check number of arguments passed to the script
function isArgumentPresent {
  if [  -gt 0 ]
  then
    return 0	# success code
  else
    return 1	# failure code
  fi
}
# calling the function
# and passing number of arguments passed to the script
isArgumentPresent $#
# get the returned code
returnedCode=$?
# check returnedCode
if [ $returnedCode -eq 0 ]
then
  echo "Arguments present!"
else
  echo "Arguments not present!"
fi

说明:

在上面的脚本中,我们使用 $0变量来获取脚本文件的名称,即。
example01.sh.

我们正在使用 $#命令获取传递到脚本文件的参数总数。

我们使用if语句检查用户是否向脚本提供了任何参数。
如果$为0,则返回 No argument provided to the script.

如果用户向脚本文件提供1个或者多个参数,那么$大于0,因此,我们使用for循环来选取存储在变量中的每个参数 $@并将其赋给变量 arg.

然后,在for循环的主体中,我们回显每个参数。

Shell $?变量

此变量保存上次运行命令或者函数返回代码的退出值。

例如,如果我们调用一个函数,该函数应该返回任何值,那么我们可以使用 $?变量。

示例2:编写一个Shell脚本,根据函数调用的返回值显示一些结果

在下面的示例中,我们检查参数是否基于函数调用的返回代码提供。

$sh example02.sh hello world
Arguments present!
$sh example02.sh 
Arguments not present!
#!/bin/sh
echo "PID of the current file is $$"

Shell $$变量

此变量保存当前运行脚本的PID,即"进程标识符"。

PID的一个用例是在从脚本创建临时文件时添加它。

示例:临时文件-$.tmp

示例#3:编写Shell脚本以打印当前运行脚本的PID

$sh example03.sh 
PID of the current file is 71084
#!/bin/sh
echo "The PID of the last run background process was $!"

Shell $!变量

此变量保存上次运行的后台进程的PID。

示例#4:编写Shell脚本以打印上次运行的后台进程的PID

$sh example04.sh 
The PID of the last run background process was 84014
##代码##