Hacker News new | ask | show | jobs
by woodrowbarlow 3276 days ago
> Quoting is building execve's argv parameter.

can you expand on this? does this elucidate, e.g., variable substitution and the difference between single- and double-quotes? or does it just help demonstrate when you need quotes for an argument that may contain whitespace?

1 comments

The behavior of quotes can and should be described in terms of how they affect the words they expand to (i.e. the argv you build), so yes, it clarifies all this.

For example, all the various wrong ways of quoting var="My File.txt" or otherwise incorrectly using such a name will result in variations on a wrong argument list:

  execlp("cat", "$var", NULL);            // cat '$var'
  execlp("cat", "My", "File.txt", NULL);  // cat $var
  execlp("cat My File.txt", NULL);        // cmd="cat $var"; "$cmd"
  execlp("cat", "'My", "File.txt'", NULL);// cmd="cat '$var'"; $cmd
  execlp("cat", "My\\", "File.txt", NULL);// cmd="cat My\ File.txt"; $cmd
  execlp("cat", "'My File.txt'", NULL);   // var="'$var'"; cat "$var"
  execlp("cat", "\"$var\"", NULL);        // arg='"$var"'; cat $arg

Meanwhile, all the correct ones result in the same, correct argv:

  execlp("cat", "My File.txt", NULL);  // cat "$var"
  execlp("cat", "My File.txt", NULL);  // cat 'My File.txt'
  execlp("cat", "My File.txt", NULL);  // cat "My File.txt"
  execlp("cat", "My File.txt", NULL);  // cat My\ File.txt
  execlp("cat", "My File.txt", NULL);  // cmd=("cat" "$var"); "${cmd[@]}"
  execlp("cat", "My File.txt", NULL);  // arg="'My File.txt'"; eval "cat $arg"
If you don't know which argument list you're aiming for, you basically have to go by guesswork and superstitions.