I'm trying to return a custom exit code (and subsequently display an error message) when there is no match for the value I'm trying to find. I found the following previous stackoverflow question - Return code of sed for no match, which I used to develop the following script.
update_value() {
local before="$1"
local after="$2"
sed -i "/$before/!{q100}; {s/$before/$after/}" "$3"
local sed_exit_code="$?"
if [[ "$sed_exit_code" -eq 100 ]]; then
echo "ERROR: There is no $before value in $3"
exit 1
elif [[ "$sed_exit_code" -ne 0 ]]; then
echo "Error updating $before value in $3"
exit 1
else
echo "Successfully updated $before to $after in $3"
fi
}
update_value x y file.txt
I'm running this on
CentOS Linux release 7.7.1908 (Core)
, with sed version (sed (GNU sed) 4.2.2
), and it is returning the first error (ERROR: There is no x value in file.txt
) despite there definitely being an x value in that file.
Therefore, sed is returning exit code 100 incorrectly. What am I missing/doing wrong here?