0

From a command I get some arguments that I want to offer to the user with the select statement from bash in a shell script. The arguments supplied by the command may contain spaces and are therefore protected by quotes. Here is a simplified example.

This works as expected:

select opt in a b "c d"
do
  echo $opt
  break
done

The output is as expected:

1) a
2) b
3) c d
#? 

But with the output from the command in a variable it does not work as expected:

opts="a b \"c d\""
select opt in $opts
do
  echo $opt
  break
done

Although $opts contains the same as the hard coded typing in the first select-example the output is different:

1) a
2) b
3) "c
4) d"
#?

So it's not that bash consumed the quotes. They are kept, but the quotes do not encapsulate an argument as they did when I hard coded them. As I already wrote I get the arguments as output from a command. They may contain spaces and are therefore already protected by quotes. How do I get them in one piece to the 'select' statement? It is not about single and double quotes. With single quotes the same happens:

1) a
2) b
3) 'c
4) d'
#?
0

This solution should help you:

#!/bin/bash

opts=(a b "c d");

select opt in "${opts[@]}"
   do echo $opt; 
   break; 
done
  • Yes, this works. Thanks. I'm now working on getting the output from the command in one piece into $opts. Also there it is split up into array elements at the spaces even between quotes. – Markus Dec 29 '14 at 15:45
0

Use an array:

opts=("a" "b" "c d");select opt in "${opts[@]}"; do echo $opt; break; done
  • Yes, that works. Thanks. It's the same solution as that from @podwysoc – Markus Dec 29 '14 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.