shell脚本中的参数处理

时间:2014-05-28 22:09:23

标签: linux bash shell

我有一个简单的shell脚本,它接受2个参数(名称和年龄),将参数赋给变量并打印变量 如果我只传递没有名字的年龄值,变量" vname"被赋予年龄值 但是我想为vname和age分配名称。如果没有传递名称,vname变量不应该有任何值。任何人都可以告诉我如何实现它?

#!/bin/bash

vname=$1
vage=$2
echo $vname
echo $vage

1 个答案:

答案 0 :(得分:0)

#!/bin/bash
echo $#
#### the number $# tests the number of arguments
## you can use it to create a loop or do the following 

if [[ $1 = *[[:digit:]]* ]]; then
 echo " Arg1  is numeric"
# assign Arg1 to age here .... (not coding for you)
else
 echo "Arg1 is not numeric"
     if [[ $2 = *[[:digit:]]* ]]; then
        echo " Arg2  is numeric"
  else
        echo "Arg2 is not numeric"
    fi
fi

我将此代码保存为“name_and_age.sh”并运行它:

./name_and_age.sh as 2
2
Arg1 is not numeric
 Arg2  is numeric