shell脚本的参数问题

今天药忘吃喽~ 2022-08-06 15:05 266阅读 0赞

一个简单例子

para.sh
########################
#!/bin/sh
#scriptname:para

echo “this script is call $0”
echo “$0 $1 $2”
echo “The number of positionalparameters is $#“

echo “$* is the dollar star”

echo “$@ is the dollar at”

echo “ “$*“ is the dollar star which has quoation marks”

echo “ “$@” is the dollar at which has quoation marks”
################
[root@yqrh5u2]chmod +x para.sh
[root@yqrh5u2 rbf]# ./para.sh 1st_name 2nd_para 3rd_last
this script is call ./para.sh
./para.sh 1st_name 2nd_para
The number of positionalparameters is 3
1st_name 2nd_para 3rd_last is the dollar star
1st_name 2nd_para 3rd_last is the dollar at
1st_name 2nd_para 3rd_last is the dollar star which has quoation marks
1st_name 2nd_para 3rd_last is the dollar at which has quoation marks

Positional Parameter What It References

$0 References the name of the script,脚本的名称

$# Holds the value of the number of positional parameters,参数的个数

$* Lists all of the positional parameters,列出所有的参数

$@ Means the same as $*, except when enclosed in double quotes

“$*“ Expands to a single argument (e.g., “$1 $2 $3”),

“$@” Expands to separate arguments (e.g., “$1” “$2” “$3”)

$1 .. $9 References up to nine positional parameters,应用对应的参数

$* and $@ 区别,只有单他们有双引号是才有区别:
$ set ‘apple pie’ pears peaches

6 $ for i in $@

  1. > do
  2. > echo $i
  3. > done
  4. apple
  5. pie
  6. pears
  7. peaches

7 $ set ‘apple pie’ pears peaches
8 $ for i in “$@” # At last!!

  1. > do
  2. > echo $i
  3. > done
  4. apple pie
  5. pears
  6. peaches

脚本的参数至少是1,
name=${1:?”requires an argument” }

echo Hello $name
:? 将会检验$1是否有值,加入没有,脚本退出,并且报错误信息。

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Shell脚本参数传递

    > 在许多的情况下,Shell脚本都需要接受用户的输入,根据用户的输入参数来执行不同的操作。本节内容主要介绍Shell脚本的参数,以及如何在脚本中接收参数。 Shell脚本