Variable containing multiple args with quotes in Bash

岁酱吖の 提交于 2019-11-27 06:53:59

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.)

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.

Here is my recipe to concat quoted arguments - mostly used to keep the script readable. But it's also comfortable to comment some arguments out easily:

PARAM1="a param with white spaces"
PARAM2="some other funny param"
PARAM3="third spaced param"
#...

PARAMS=$PARAM1
PARAMS+='" "'
PARAMS+=$PARAM2
PARAMS+='" "'
PARAMS+=$PARAM3
#...

eval command '"'$PARAMS'"'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!