linux shell 多种数据类型传参,并用if判断传入的参数,举个例子
时间: 2023-02-14 17:57:39 浏览: 162
在Linux shell中,可以使用多种数据类型作为参数传递。例如,可以传递字符串、数字、布尔值等。
使用if语句判断传入的参数类型,可以使用test命令或者[ ]来进行判断,如下例:
```
#!/bin/bash
if [ $1 -eq 0 ]
then
echo "The first argument is 0."
elif [ $1 -lt 0 ]
then
echo "The first argument is negative."
else
echo "The first argument is positive."
fi
```
上面的脚本中,第一个参数被传入到$1中,然后使用[ $1 -eq 0 ]来判断传入的参数是否等于0,如果是,则输出"The first argument is 0."。
另一个例子
```
#!/bin/bash
if test $1 = "hello"; then
echo "The first argument is hello"
else
echo "The first argument is not hello"
fi
```
上面的脚本中,第一个参数被传入到$1中,然后使用test $1 = "hello"来判断传入的参数是否等于hello,如果是,则输出"The first argument is hello"。
相关问题
linux 写一个shell脚本 传入字符串、整形、boolean、浮点数,并用if判断传入的参数,并用sh执行,给出具体例子
```bash
#!/bin/sh
string_param=$1
int_param=$2
bool_param=$3
float_param=$4
if [ -z "$string_param" ]
then
echo "缺少字符串参数"
exit 1
fi
if [ -z "$int_param" ] || ! [[ "$int_param" =~ ^[0-9]+$ ]]
then
echo "缺少整数参数或参数不是整数"
exit 1
fi
if [ -z "$bool_param" ] || ! [[ "$bool_param" =~ ^(true|false)$ ]]
then
echo "缺少布尔参数或参数不是布尔值"
exit 1
fi
if [ -z "$float_param" ] || ! [[ "$float_param" =~ ^[0-9]+(\.[0-9]+)?$ ]]
then
echo "缺少浮点数参数或参数不是浮点数"
exit 1
fi
echo "字符串参数: $string_param"
echo "整数参数: $int_param"
echo "布尔参数: $bool_param"
echo "浮点数参数: $float_param"
```
使用方法:
```sh
sh test.sh "hello world" 123 true 3.14
```
输出:
```
字符串参数: hello world
整数参数: 123
布尔参数: true
浮点数参数: 3.14
```
说明:
- 首先判断传入的参数是否为空,如果为空则退出程序并提示缺少该参数
- 利用正则表达式判断参数是否为整数、布尔值、浮点数
- 最后输出传入的参数
linux 写一个shell脚本 传入字符串、整形、boolean、浮点数,并用if判断传入的参数等于几,并用sh执行,给出具体例子
下面是一个示例 shell 脚本,它接受字符串、整数、布尔值和浮点数作为参数,并使用 if 判断传入的参数是否等于某个值:
```
#!/bin/sh
string_param="$1"
int_param="$2"
bool_param="$3"
float_param="$4"
if [ "$string_param" = "hello" ]; then
echo "The string parameter is 'hello'"
fi
if [ "$int_param" -eq 10 ]; then
echo "The integer parameter is 10"
fi
if [ "$bool_param" = "true" ]; then
echo "The boolean parameter is 'true'"
fi
if [ $(echo "$float_param == 3.14" | bc) -eq 1 ]; then
echo "The float parameter is 3.14"
fi
```
执行脚本:
```
sh script.sh hello 10 true 3.14
```
输出:
```
The string parameter is 'hello'
The integer parameter is 10
The boolean parameter is 'true'
The float parameter is 3.14
```
请注意,在判断浮点数参数时,我们使用了 bc 命令来比较浮点数的值。