0

I don't understand why my shell script doesn't work.

#!/bin/sh

getProjectsNames() {
   list=`ls -a`
   return $list
}

projectsNames=`getProjectsNames`
echo $projectsNames

This code is returning error:

script.sh: 6: return: Illegal number: .

Thanks for your help!

iBug
  • 35,554
  • 7
  • 89
  • 134
ken
  • 127
  • 3
  • 8

2 Answers2

0

In Unix shells, the return statement can only return a number that's eligible to be the exit code of a program. In most Linux and Unix systems, it's between 0 and 255.

If you want to pass a string, use stdout and output capturing:

#!/bin/sh

getProjectsNames() {
    list=`ls -a`
    echo "$list"
}

projectsNames=$(getProjectsNames)

Note the change from return $list to echo "$list".

iBug
  • 35,554
  • 7
  • 89
  • 134
0

Its because return expects a numerical value, see from manual return [n] : Causes a function to exit with the return value specified by n

so if you want to capture something which returns from function, use echo, for example,

    #!/bin/sh

    getProjectsNames() {
        list=$(ls -a)
        echo "$list"
    }

    projectsNames=$(getProjectsNames)
    echo $projectsNames

see more here in this link, StackOverFlow

Jithin Scaria
  • 1,271
  • 1
  • 15
  • 26