我有一个简单的 shell 脚本,它接受 2 个参数(姓名和年龄),将参数分配给变量并打印变量 如果我仅传递没有名称的年龄值,则为变量“vname”分配年龄值 但我想将名称分配给 vname,将年龄分配给 vage。如果没有传递名称,则 vname 变量不应该有任何值。任何人都可以让我知道如何实现这一点吗?
#!/bin/bash
vname=$1
vage=$2
echo $vname
echo $vage
最佳答案
#!/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
关于linux - shell脚本中的参数处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922711/