2

I cannot find a solution to this particular problem, even though more or less similar questions have been questioned before in:

Running a script from bash is easy enough, however once one needs user interaction I couldn't find a solution. Please consider the example:

userInput<-function(question) {
  n = 0
  while(n < 1 ){
    n <- readline(question)
    n <- ifelse(grepl("\\D",n),-1,as.integer(n))
    if(is.na(n)){break}  # breaks when hit enter
  }
  return(n)
}

investedLow<- userInput("Invested value in low risk since last time: ")

Now if I save this script as test.R and run it for R --no-save < teste.R the entire script is run and the time for user input does not happen.

The script works fine in Rstudio, for example.

  • How to wait for user input in a script to be run in the command line?
lf_araujo
  • 1,991
  • 2
  • 16
  • 39

1 Answers1

3

Here is a total hack, repurposing a very specific purpose-built package for your more-general question:

library(getPass)
userInput<-function(question) {
    n = 0
    while(n < 1 ){
        n <- getPass::getPass(msg = question)
        n <- ifelse(grepl("\\D",n),-1,as.integer(n))
        if(is.na(n)){break}  # breaks when hit enter
    }
    return(n)
}

investedLow <- userInput("Invested value in low risk since last time: ")
print(investedLow)

Maybe the worst part about this is that getPass hides the user input. There must be a way to modify the source code to fix that.

Update: The getPass author pointed out that the solution could be as simple as using readLines slightly differently:

cat(question)
readLines(file("stdin"), n=1)
zkurtz
  • 3,230
  • 7
  • 28
  • 64