Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A Bash function can't return a string directly like you want it to. You can do three things:</p> <ol> <li>Echo a string</li> <li>Return an exit status, which is a number, not a string</li> <li>Share a variable</li> </ol> <p>This is also true for some other shells.</p> <p>Here's how to do each of those options:</p> <h2>1. Echo strings</h2> <pre><code>lockdir="somedir" testlock(){ retval="" if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo &gt;&amp;2 "successfully acquired lock: $lockdir" retval="true" else echo &gt;&amp;2 "cannot acquire lock, giving up on $lockdir" retval="false" fi echo "$retval" } retval=$( testlock ) if [ "$retval" == "true" ] then echo "directory not created" else echo "directory already created" fi </code></pre> <h2>2. Return exit status</h2> <pre><code>lockdir="somedir" testlock(){ if mkdir "$lockdir" then # Directory did not exist, but was created successfully echo &gt;&amp;2 "successfully acquired lock: $lockdir" retval=0 else echo &gt;&amp;2 "cannot acquire lock, giving up on $lockdir" retval=1 fi return "$retval" } testlock retval=$? if [ "$retval" == 0 ] then echo "directory not created" else echo "directory already created" fi </code></pre> <h2>3. Share variable</h2> <pre><code>lockdir="somedir" retval=-1 testlock(){ if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo &gt;&amp;2 "successfully acquired lock: $lockdir" retval=0 else echo &gt;&amp;2 "cannot acquire lock, giving up on $lockdir" retval=1 fi } testlock if [ "$retval" == 0 ] then echo "directory not created" else echo "directory already created" fi </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload