glcui 发表于 2018-8-22 08:50:22

shell 中 的位置变量

  shell 中常见的位置参数如下
  $# : 用来统计参数的个数
  $@ :会将命令行的所有的参数当做同一个字符串中的多个独立单词
  $* :会将命令行的参数当做一个参数来保存
  举例说明
  参数 $#
cat test8.sh  
#!/bin/bash
  
## getting the unmber of parameters
  

  
#
  
echo there are $# parameters supplied
  ./test8.sh 1 2 3
  there are 3 parameters supplied
  参数的简单运算,当输入正确的参数时进行运算、错误的时候输入脚本用法
#!/bin/bash  
## testing parameters
  
#
  

  
if [ $# -ne 2]
  
then
  
echo Usage: test9.sh a b
  
else
  
total=$[ $1 + $2]
  
echo The total is $total
  
#echo
  
fi
  ./test9.sh 8 56
  The total is 64
  ./test9.sh 81
  Usage: test9.sh a b
  参数$@ 和$#
#!/bin/bash  
#testing $* and $@
  
echo
  
#echo "Using the $* method: $*"
  
echo "Using the \$* method: $*"
  
echo
  
echo "Using the \$@ method: $@"
  ./test11.sh aa bb cc
  Using the $* method: aa bb cc
  Using the $@ method: aa bb cc
  上述例子表面上$@ 和$# 的用法是一样的,下面的例子将会加以区分
#!/bin/bash  
# testing $* and $@
  
#
  
echo
  
count=1
  

  
#
  
for param in "$*"
  
do
  
echo "\$* parameter #$count = $param"
  
count=$[ $count + 1 ]
  
done
  

  
echo "-------------------------------------"
  
#
  
for param in "$@"
  
do
  
echo "\$@ parameter #$count = $param"
  
count=$[ $count + 1 ]
  
done
  ./test12.sh aa bb cc dd
  $* parameter #1 = aa bb cc dd
  -------------------------------------
  $@ parameter #2 = aa
  $@ parameter #3 = bb
  $@ parameter #4 = cc
  $@ parameter #5 = dd


页: [1]
查看完整版本: shell 中 的位置变量