1

This is my bash script. I want to pass a command as an argument and run it.

  • case 1) is not working
  • case 2) is working well.

How can I make case 1) work?

function menu(){
    echo "[$@]"
    declare -a myarray
    while IFS= read -r input; do
      result_array+=( "$input" )
      ((count++))
      printf "[$count] %s\n" "${input[0]}"
    done < <( $@ ) ########### case1) I want to use but it is not working.
    ## done < <( "find . -name '*.bak'" ) ########## case2) working well 
}


## main 
menu "find . -name '*.bak'" 

I tried every shell variable expansion I know but it ended up failure.

OfusJK
  • 676
  • 1
  • 5
  • 13
  • How is it not working? What happens, and what would you like to happen instead? Can you remove everything that works and only leave the exact minimal code the has the problematic behaviour ([mcve])? – Benjamin W. Jan 28 '22 at 17:03
  • Ok, I will make it small. – OfusJK Jan 28 '22 at 17:05
  • I don't understand what you want. It seems to me that you want `find . -name '*.bak' | while IFS= read -r input; do .....` Or did I miss something? – Ljm Dullaart Jan 28 '22 at 17:10
  • ( $@ ) make sub-shell and run it, and then redirect to while. – OfusJK Jan 28 '22 at 17:26
  • Side note: have a look at the `select` built-in, it does pretty exactly what you're trying to recreate with your `menu` function. – Benjamin W. Jan 28 '22 at 23:07

1 Answers1

1
done < <( $@ )

Make sure to quote "$@". If you don't quite it then it will be subject to glob expansion and *.bak could be expanded to the names of all the backup files in the current directory.

done < <("$@")

Then you'll also want to pass in the command as separate arguments rather than a single string. Which is easy: drop the surrounding quotes.

menu find . -name '*.bak'
John Kugelman
  • 349,597
  • 67
  • 533
  • 578