0

I want to define a variable representing the switches for some program to be run later. One of those switches needs a filename argument, where the filename may contain spaces or special characters. How do I do something like this properly?

#! /bin/bash

FILE="/home/user/Excludes (1).txt"
SWITCHES="--verbose --exclude $FILE"  # both this and \"$FILE\" here fail.

someprogram $SWITCHES

Here is a real world example of trying to define a string in bash, that contains another string (though here the second one is an argument, rather than a switch):

$ cat > "foo bar"
me "foo bar"

$ FOOBAR="foo bar"
$ SWITCHES="-n $FOOBAR"

$ cat $SWITCHES
cat: foo: No such file or directory
cat: bar: No such file or directory

$ cat "$SWITCHES"
cat: invalid option -- ' '
Try 'cat --help' for more information.

$ SWITCHES="-n \"$FOOBAR\""

$ cat $SWITCHES
cat: '"foo': No such file or directory
cat: 'bar"': No such file or directory

$ cat "$SWITCHES"
cat: invalid option -- ' '
Try 'cat --help' for more information.
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Diagon
  • 473
  • 5
  • 16
  • 1
    Use an array instead of a string for this. See [BashFAQ #50](https://mywiki.wooledge.org/BashFAQ/050) – Charles Duffy Aug 12 '22 at 12:42
  • 1
    `switches=( --verbose --exclude "$file" )`, then `rsync "${switches[@]}"` – Charles Duffy Aug 12 '22 at 12:45
  • Note the use of lower case variable names -- that's specified by POSIX to prevent people from mistakenly overwriting names meaningful to the shell or operating system, which are all-caps. – Charles Duffy Aug 12 '22 at 12:46
  • I see. Ok, thank you. I feel like I should leave this question, because I couldn't find anything similar; but was it too simple? Should I delete? If not, and you don't want to, I could work up an answer. @CharlesDuffy – Diagon Aug 12 '22 at 12:50
  • 1
    I'm pretty sure there's a better duplicate already in the knowledge base; I can try to find one to close it with something closer. – Charles Duffy Aug 12 '22 at 12:51
  • 1
    SWITCHES="-n \"$FOOBAR\""; eval cat $SWITCHES – Haru Suzuki Aug 12 '22 at 17:29
  • That struck me as a cool hack, but now I understand we should [avoid 'eval'](https://stackoverflow.com/a/11079387/1618452) if at all possible. – Diagon Aug 13 '22 at 02:47

0 Answers0