You are here

Quoting options in bash paramenters

I have spend hours searching for the answer to this problem, so now I have found it I will post it.

Demonstrate problem

Suppose I have a program that takes an option in the form:

myprog -t "Title of Document"

To test this we will create a script: testopt.sh

#!/bin/bash
echo option: «$1», title: «$2», ignore: «$3»

When we run it we get:

./testopt.sh  -t "Title of Document"
>> option: «-t», title: «Title of Document», ignore: «»

The problem shows up if instead of passing the arguments directly, we use a variable:

opt='-t "Title of Document"'
./testopt.sh  $opt
>> option: «-t», title: «"Title», ignore: «of»

Reasons for Problem

Bash parses the line in multiple passes. Grouping into tokens using " is done before variable expansion, so the grouping withing the opt variable is ignored. This is documented very well here:

Solution

  • The eval command!
  • When calling the script, force a re-parsing of $opt
eval ./testopt.sh  $opt
>> option: «-t», title: «Title of Document», ignore: «»
  • Note that once inside testopt.sh it is too late to change things, since the arguments are already split up
Topic: