0

I am trying to write a script that allows a user to input a number and change an xdotool key value to that input. Key inputs in xdotool must be separated by a space, for example

xdotool key 1 2 8;

So I know I need to use sed to change the input to the correct format

$variable | sed 's/./& /g'

Here is where I run into the issue, say my code is

read -p 'Enter Number: ' enum
read -p 'Enter a number of times to run loop: ' loopnum
for (( i = 1; i<= loopnum; ++i )); do

xdotool mousemove  1000 785 click 1 click 1;
xdotool key $enum_with_spaces;
done

How do I get $enum_with_spaces to actually replace with the input with spaces?

1
  • 1
    What is $variable? Is it a command? If not, $variable | sed 's/./& /g' doesn't make sense. And what are you expecting the user to input? A single number? Multiple numbers?
    – terdon
    Commented Apr 24, 2023 at 10:32

1 Answer 1

1

First of all, don't prompt for input unless you have a very good reason to (e.g. to ask for a password which you don't want to appear in the command history). That just breaks the flow of the script, requires users to laboriously type out values, and means you cannot run the same command again or automate it easily. Instead, read the values at launch time from the script's arguments.

So a simple way would be something like this:

#!/bin/bash
## save the first argument as loopnum
loopnum=$1
## remove the first argument from the list of arguments
shift


for (( i = 1; i<= loopnum; ++i )); do
  xdotool mousemove  1000 785 click 1 click 1;
  ## Because of the 'shift' above, the aray $@ which holds the positional
  ## parameters (arguments) has everything except the loopnum, so we
  ## can pass it to xdotool
  xdotool key "$@";
done

You would then run this with the values you want it to use. For example, to make loopnum=4 and pass the keys a, j and 9, you would do:

your_script.sh 4 a j 9 

If you absolutely must pass the values without spaces, do something like this:

#!/bin/bash
## save the first argument as loopnum
loopnum=$1
## save the second argument as enum
enum=$2
## Add the spaces and save in an array
enum=( $(sed 's/./& /g' <<<"$enum") )

for (( i = 1; i<= loopnum; ++i )); do
  xdotool mousemove  1000 785 click 1 click 1;
  xdotool key "${enum[@]}"
done

And run like this:

your_script.sh 4 aj9 
1
  • FYI in bash 5.2.15 variable=123; echo "${variable//?/& }" outputs 1 2 3 so you could use "${enum//?/& }" instead of $(sed 's/./& /g' <<<"$enum") if your bash version supports it.
    – Ed Morton
    Commented Apr 24, 2023 at 12:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .