Variable containing multiple args with quotes in Bash

后端 未结 4 1414
渐次进展
渐次进展 2020-11-28 05:59

I generate a bash variable containing all my args and those args contain spaces. When I launch a command with those args - eg. ls $args - quotes are not correctly interprete

相关标签:
4条回答
  • 2020-11-28 06:34

    Use eval this will first evaluate any expansions and quoting and then execute the resultant string as if it had been typed into the shell.

    args="'$f1' '$f2'"
    eval ls $args
    

    eval will then be executing ls 'file n1' 'file n2'

    Had a very similar problem, trying to pass arguments in variables sourced from /etc/default/ to start_stop_daemon in init scripts.

    0 讨论(0)
  • 2020-11-28 06:45

    Use set to set your variables as positional parameters; then quoting will be preserved if you refer to them via "$@" or "$1", "$2", etc. Make sure to use double quotes around your variable names.

    set -- "$f1" "$f2"
    touch "$@"
    ls "$@"
    rm "$@"
    
    0 讨论(0)
  • 2020-11-28 06:51

    This is probably the worst answer, but you can change IFS. This is the "internal field separator" and is equal to space+tab+newline by default.

    #!/bin/sh
    IFS=,
    MAR="-n,my file"
    cat $MAR
    

    The script above will run cat. The first argument will be -n (numbered lines) and the second argument will be my file.

    0 讨论(0)
  • 2020-11-28 06:56

    You might consider using an array for the args, something like this:

    args=( "$f1" "$f2" )
    ls "${args[@]}"
    

    (The problem you're hitting at the moment is that once interpolation has happened there's no difference between intra- and inter- filename spaces.)

    0 讨论(0)
提交回复
热议问题