25

return statement error:urn: can only `return' from a function or sourced script in shell script myscript.sh

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

mv $1 $2

return 0

When i try to run

sh myscript.sh

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

how to fix that error ?

PhilMasteG
  • 3,095
  • 1
  • 20
  • 27
karthi keyan
  • 251
  • 1
  • 3
  • 3
  • 2
    This smells like an XY problem. If you want to know if your script is being *sourced* or *executed*, [this SO question](https://stackoverflow.com/q/2683279/7552) has some answers for you. – glenn jackman Jun 20 '18 at 16:02

1 Answers1

44

I guess you mean

exit 2

and

exit 0

Also, have a second look at the syntax of test.

PhilMasteG
  • 3,095
  • 1
  • 20
  • 27
  • this script not working on opensuse linux.works on ubuntu.There is any diffrence between ubuntu bash and opensuse bash? – karthi keyan Jun 20 '18 at 13:37
  • i want to use return statement. – karthi keyan Jun 20 '18 at 13:37
  • The error message is indicating you can't use a "return" statement as you want. Change your code to write a function (you can use return inside a function), and then check for the returned value (#?). – aicastell Jun 20 '18 at 13:48
  • Please clarify your question and state what exactly it is you are trying to do with that script. As your shell is telling you, you cannot `return` from a shell script. Exit sets the exit code and returns from the script. Alternatively use @aicastell's suggestion and wrap it in a function to be able to use `return`. – PhilMasteG Jun 20 '18 at 13:51
  • Why do you want to use the `return` statement, what do you expect it to do? When you say "not working", please describe exactly what happens. – cdarke Jun 20 '18 at 16:28
  • in SUSE terminal.return statement does not work.i dont know why?i want to know why the return statement not working in suse linux. – karthi keyan Jun 21 '18 at 06:32
  • when i try to run sh myscript.sh it gives error like sh can only returns sourced script ...how can i fix it? – karthi keyan Jun 21 '18 at 06:33
  • 2
    Like @glenn jackman commented on your question, you might have fallen for the [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – PhilMasteG Jun 21 '18 at 07:55