【问题标题】:sh return: can only `return' from a function or sourced scriptsh return:只能从函数或源脚本中“返回”
【发布时间】:2018-11-29 15:33:13
【问题描述】:

return 语句错误:urn: can only `return' from a function or sourced script in shell script 我的脚本.sh

#!/bin/bash
if [ $# -ne 2 ]
then
    echo "Incorrect Usage : Arguments mismatch."
    return 2
fi

mv $1 $2

return 0

当我尝试运行时

sh myscript.sh

Incorrect Usage : Arguments mismatch.
myscript.sh.sh: line 5: return: can only `return' from a function or sourced script

如何解决这个错误?

【问题讨论】:

  • 这听起来像是 XY 问题。如果您想知道您的脚本是sourced 还是executedthis SO question 为您提供了一些答案。

标签: linux bash shell operating-system


【解决方案1】:

我猜你是说

exit 2

exit 0

另外,再看看test 的语法。

【讨论】:

  • 这个脚本不能在opensuse linux上工作。在ubuntu上工作。ubuntu bash和opensuse bash有什么区别吗?
  • 我想使用return语句。
  • 错误信息表明您不能随意使用“return”语句。更改代码以编写函数(可以在函数内部使用 return),然后检查返回值(#?)。
  • 请澄清您的问题并说明您正在尝试使用该脚本做什么。正如你的 shell 告诉你的那样,你不能从 shell 脚本中return。 Exit 设置退出代码并从脚本返回。或者使用@aicastell 的建议并将其包装在一个函数中以便能够使用return
  • 就像@glenn jackman 对您的问题发表的评论一样,您可能已经爱上了XY Problem
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
相关资源
最近更新 更多