【问题标题】:Argument pass to file read in as 0参数传递到文件读取为 0
【发布时间】:2019-01-05 18:57:28
【问题描述】:

我有一个脚本:

#!/bin/bash
echo "You chose $1 and $2 "
if [[ $1 -eq 0 || $2 -eq 0 ]]
then
  echo "You didn't chose argument"
  exit 1
elif 

...
exit 0

在终端我试过了:

./Path/to/script argument1 argument2

结果我得到:

You chose argument1 and argument2
You didn't chose argument

我怎么可能在同一时刻返回正确的两个参数并将它们视为 0?

这里有什么问题?

【问题讨论】:

  • 注意条件有点不稳定,最好用'&&'而不是'||'来表达。
  • 您正在将字符串与数字进行比较。而是使用 if [[ -z $1 .. etc.
  • if (( $# < 2 )); then ... 应该可以解决问题。

标签: linux bash arguments


【解决方案1】:

-eq 用于 integer 比较,当您尝试将字符串与整数进行比较时,[[ 会变得有点好笑。发生的情况是 bash$1 扩展为 另一个 变量的名称并扩展 that。如果变量不存在,默认展开为0。

如果要检查字符串本身是否为零,请坚持字符串比较:

if [[ $1 = 0 || $2 = 0 ]]; then

如果您更可能想要检查是否实际提供了两个参数,请按照 mickp 的建议检查 $# 的值:

if (( $# < 2 )); then
  echo "You didn't provide 2 arguments.

另一种选择是使用${...?....} 形式的参数扩展,它会打印给定的错误消息并在未设置参数时退出。

: ${1?You need two arguments, provided none}
: ${2?You need two arguments, provided only $1}

【讨论】:

  • if (( $#
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多