Search code examples
linuxshellvariablescommandsh

Using Linux shell variable as command parameter with spaces


I'm on a synology DS218 and want to create a script to call jdupes which automatically excludes specific directories. For that I want to call

jdupes -rA -X nostr:"somepath/with spaces" -X nostr:"and/some other path" "/mydir"

but having the -X nostr:"somepath/with spaces" -X nostr:"and/some other path" part saved in a variable, because I call jdupes multiple times in the script and only want one place where I can save my excluded directories.

This is the base of what I tried:

excluded_path='-X nostr:`somepath/with spaces`'

jdupes -rAm $excluded_path "/mydir"

from that I tried different versions, for example

excluded_path="-X nostr:'somepath/with spaces'"
excluded_path="-X nostr:/"somepath/with spaces\""
excluded_path='-X nostr:"somepath/with spaces"'

and some more, each time I tried having the $excluded_path with and without ""


Solution

  • You should store command-line arguments in an array.

    excluded_path_args=(-X "nostrum:somepath/with spaces")
    
    jdupes -rA "${excluded_path_args[@]}"
    

    The -X and its argument nostrum:somepath/with spaces are two separate arguments as far as the shell is concerned. (It's jdupes that determines what those arguments mean and how to use them.) The array stores each argument as a separate element; the expansion "${...[@]}" ensures that each element is treated as a distinct word when building the argument list.