linux - shell脚本中的参数处理

标签 linux bash shell

我有一个简单的 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/

相关文章:

linux - 字符串中的 Shell 脚本参数

linux - <命令行> :0:1: error: macro names must be identifiers . ......这个错误的解决方案?

c++ - 链接失败,怎么回事?

bash shell 嵌套 for 循环

bash ->/dev/null 如何消耗输出流?

shell - 如何在配置单元中调用shell脚本

linux - Ubuntu服务器 "sudo"错误AWS EC2

linux - 排序文件仅获取行最大值

python - 有没有办法同时用一个脚本运行多个 bash 脚本?

android - 从 Android 应用程序运行 shell 脚本