Wednesday, November 27, 2019

command line - weird shell script error: invalid option return: usage: return [n]


This programme checks if a certain book title exist by matching user input of book title and book author.


function removebook_option()
{
echo -n "Title : "
read title_input2
echo -n "Author: "
read author_input2
checkexist $title_input2 $author_input2
error=$?
echo "$error"
if [ $error != -1 ];then
#removebook
echo "New book title $title_input removed successfully"
else
echo "Book does not exist"
fi
}
function checkexist()
{
counter=0
for x in ${title[@]}
do
for y in ${author[@]}
do
if [ $x == $1 ] && [ $y == $2 ];
then
error=$counter
return "$error"
fi
done
counter=$((counter+1))
done
error=-1
return "$error"
}
title=(foo1 foo2)
author=(bar1 bar2)
removebook_option

I am getting a very weird error , where function checkexist() returns 2 instead of -1 when there isnt a match which happens when returning value error=-1



line 43: return: -1: invalid option return: usage: return [n]



EDIT : For reasons unknown , i can only return values from 0-255 , does anyone know how to return negative values??


You can try to input incorrect data to see the weird error


I need help resolving this issue thanks!!!!



You're getting this error:


line 43: return: -1: invalid option return: usage: return [n]

This is because the -1 is interpreted as an option. Use this, -- means 'end of options':


return -- -1

which returns with 255.




Working solution:


#!/bin/bash
function removebook_option()
{
echo -n "Title : "
read title_input2
echo -n "Author: "
read author_input2
error="$(checkexist "$title_input2" "$author_input2")" # <--
echo "$error"
if [[ "$error" != NOT_FOUND ]]; then # <--
#removebook
echo "New book title $title_input removed successfully"
else
echo "Book does not exist"
fi
}
function checkexist()
{
counter=0
for x in "${title[@]}" # <--
do
for y in "${author[@]}" # <--
do
if [[ $x == $1 ]] && [[ $y == $2 ]]; # <--
then
error=$counter
echo "$error" # <--
return
fi
done
((counter++)) # <--
done
error=NOT_FOUND # <--
echo "$error"
return
}
title=(foo1 foo2)
author=(bar1 bar2)
removebook_option

Edits marked with  # <--


This works by instead of returning an integer value, it echoes it (writes to screen). Usually, this would print to the terminal however the $( ... ) syntax captures the printed output, and assigns it to error in removebook_option(). This allows 'returning' any string, I've made it return a sentinel value of NOT_FOUND if not found.


Notes:



  • Array expansion should be wrapped with double quotes: "${author[@]}" and "${title[@]}"

  • Use [[ ... ]] instead of [ ... ].


No comments:

Post a Comment

11.10 - Can&#39;t boot from USB after installing Ubuntu

I bought a Samsung series 5 notebook and a very strange thing happened: I installed Ubuntu 11.10 from a usb pen drive but when I restarted (...