简体   繁体   中英

Return value and kill subshell function bash

#!/bin/bash

declare -i y=0
declare -i x=0
clear
echo "*"

function move (){
 while true
 do

 if [ "$1" = "d" ];
 then
 let x++
 fi
 
 if [ "$1" = "a" ];
 then
 let x--
 fi

 tput clear
 tput cup $y $x; echo "*"
 sleep 0.30s
 done
}

while true
do
read -s -n 1 key

if [ "$key" != "$last_key" ];
then
case "$key" in
 [d-D])
 move "$key" &
 ;;
 [a-A])
 ##SOMETHING
 ;;
esac
fi
last_key="$key"
done

I have a function called 'move' that loops print '*' in the background I want to stop the function 'move' when I press a different key and get 'x' and 'y' values, so i can call it again when I press a different key

The requirement seems to be able to control the the movement of a pointer that is continuously moving by entering the direction of movement via the keyboard. The OP implementation uses a background process.

The problem with the background process is that the parent and child (background) process do not share any variables. The child process inherit the initial values from the parent.

To implement such a logic, better to implement non-blocking read, instead of unconditional sleep. The code should also use the current "key" value to decide on how to move the cursor, instead of branching on the input parameter '$1'

declare -i y=0
declare -i x=0
clear
echo "*"

function move {
    local inp key=
    while true ; do
        # Read (with timeout) input and store in key
        read -n1 -t0.30 inp && key=$inp

        # Move the cursor
       if [ "$key" = "d" ]; then let x++ ; fi
       if [ "$key" = "a" ]; then let x-- ; fi

       # Update screen
       tput clear
       tput cup $y $x; echo "*"

    # Remove: sleep 0.30s
    done
}

move

Using this approach, there is no need for the parent process to handle the input. The current loop logic (while true; ... ; case... ; done), can be replaced with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM