I'm trying to write a simple script that read from standard input, using ;
character as delimiter to terminate the input line and that allows user to edit line.
Here is my test script:
#!/bin/bash
while true; do
read -e -d ";" -t 180 -p "><> " srcCommand
if [ $? != 0 ]; then
echo "end;"
echo ""
exit 0
fi
case "$srcCommand" in
startApp)
echo "startApp command";;
stopApp)
echo "stopApp command";;
end)
echo ""
exit 0
;;
*)
echo "unknown command";;
esac
done
This works but doesn't print the delimiter ';' char:
# bash test.sh
><> startApp
startApp command
><> stopApp
stopApp command
><> end
If I remove -e option it prints out ;
but user can't correct his mistake using backspace character and echoed strings are just right after the delimiter:
# bash test.sh
><> startApp;startApp command
><> stopApp;stopApp command
><> end;
How can I print out the delimiter character and allow user to edit line while reading standard input?
This is the expected behavior:
# bash test.sh
><> startApp;
startApp command
><> stopApp;
stopApp command
><> end;
Thanks
Best Answer
I'd use
zsh
where the line editor has many more capabilities and is a lot more customizable:With
bash-4.3
or above, you can do something similar with a hack like:Note that in that version, the
;
is always inserted at the end of the input buffer, not at the current cursor position. Change theadd_semicolon
to:If you want it inserted at the cursor and everything on the right discarded. Or:
if you want to insert it at the cursor but want to preserve what's on the right like in the
zsh
approach.If you don't want the
;
in$srcCommand
, you can always strip it afterwards withsrcCommand="${srcComman//;}"
for instance, but you'd need to insert it in the widget for it to be displayed byzle
/readline
.