运行Docker容器的交互式Bash脚本触发整数表达式预期报错
错误产生原因
报错的核心是Shell条件判断的操作符使用错误,同时脚本存在变量引用不规范的隐患:
-eq是Shell中专门用于整数数值比较的操作符,仅支持两个整数类型的值对比。你在判断中用-eq对比$d和字符串yes/no时,Shell无法将字符串解析为整数,就会抛出integer expression expected的错误。- 原脚本中所有读取的变量都没有加双引号包裹,如果用户输入空内容、或者带空格的镜像名/容器名,会触发条件判断语法错误、Docker命令参数拆分错误。
- 额外小问题:提示文本里的
detatch是拼写错误,正确写法是detach(后台分离模式)。
修正方案
字符串比较需要使用=操作符(POSIX标准,全Shell兼容),同时给所有变量引用加上双引号,read命令加上-r参数避免反斜杠被意外转义,修正后的完整脚本如下:
#!/bin/bash echo "Enter the name of the image whose container you want to run: " read -r container echo "Enter a name for this container: " read -r name echo "Do you want to run in detach mode? (yes/no): " read -r d if [ "$d" = "yes" ] then docker run --name "$name" -P -d "$container" elif [ "$d" = "no" ] then docker run --name "$name" -P "$container" else echo "invalid input" fi
可选优化
如果需要兼容用户的大小写输入(比如输入YES/Yes/y也能识别为确认,NO/n识别为否认),可以把判断逻辑调整为统一转小写后做正则匹配,容错性更好:
#!/bin/bash echo "Enter the name of the image whose container you want to run: " read -r container echo "Enter a name for this container: " read -r name echo "Do you want to run in detach mode? (yes/no): " read -r d # 统一将输入转为小写 d_lower=$(echo "$d" | tr '[:upper:]' '[:lower:]') if [[ "$d_lower" =~ ^(yes|y)$ ]] then docker run --name "$name" -P -d "$container" elif [[ "$d_lower" =~ ^(no|n)$ ]] then docker run --name "$name" -P "$container" else echo "invalid input, please enter yes or no" fi
注:
[[ ]]是Bash原生支持的条件判断语法,支持正则匹配,在你指定#!/bin/bash作为解释器的环境下可以正常使用。
内容的提问来源于stack exchange,提问作者Sylvain Atanga
相关产品推荐
相关产品推荐

