linux 写一个shell脚本 传入字符串、整形、boolean、浮点数,并用if判断传入的参数等于几,并用sh执行,给出具体例子
时间: 2023-02-14 11:59:38 浏览: 63
下面是一个示例 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 命令来比较浮点数的值。
相关问题
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
```
说明:
- 首先判断传入的参数是否为空,如果为空则退出程序并提示缺少该参数
- 利用正则表达式判断参数是否为整数、布尔值、浮点数
- 最后输出传入的参数
用Java写一个判断字符串是否等于对应字符方法
可以使用Java中的equals()方法来判断字符串是否等于对应字符。具体实现代码如下:
public static boolean isEqual(String str, char ch) {
return str.equals(String.valueOf(ch));
}
其中,str为需要判断的字符串,ch为对应的字符。该方法返回一个布尔值,表示字符串是否等于对应字符。