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
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.
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 "$@"
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
.
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.)