WelcomeWelcome | FAQFAQ | DownloadsDownloads | WikiWiki

Author Topic: a shell repl function  (Read 1398 times)

Offline mocore

  • Hero Member
  • *****
  • Posts: 642
  • ~.~
a shell repl function
« on: April 06, 2023, 07:08:22 AM »

Quote
A read–eval–print loop (REPL), is a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user;
https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop

this script its self dose nothing especially useful atm  ;)
and is just a modified form of example from the create-a-repl-out-of-a-command-in-bash SO post ...

https://stackoverflow.com/questions/39051951/create-a-repl-out-of-a-command-in-bash/39052025#39052025

Code: [Select]
repl() {
# ref  https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop
# ref https://unix.stackexchange.com/questions/635778/how-to-expand-variables-inside-read
# ref https://stackoverflow.com/questions/39051951/create-a-repl-out-of-a-command-in-bash/39052025#39052025

        def_ifs=$IFS;
        cmd="${1-eval}";
         # loop forever       
        while true ; do
          # read line
         while IFS="" read -r -d $'\n' -p "$cmd> " options; do
                      # remove read -e  option
                      # ash: read: line 36: illegal option -e

          #IFS="$def_ifs";
          [ "${options:1:1}" == " " ] && {  # second char is ' ' space
           first_char="${options:0:1}"
           case $first_char in
            c) # change repl command
               o=${options#* }; # shift removing first arg 'c'
               cmd=${o%% *};    # first arg is cmd
               options=${o#* }; # shift removing first arg / cmd
             ;;
           esac
          }

        #echo "cmd:$cmd opt:$options"

        first_arg=${options%% *}
        other_args=${options#* }
         case "$first_arg" in
           "quit") return 0 ;;
           "exit") return $? ;; # dont close the terminal ! just return =]
           "z") echo first arg is z other args are : $other_args ;;
           ""|'') echo empty string ;;
           *)      $cmd "$options" ;; # run command
           esac;

         done;
       done;
}