Variable containing multiple args with quotes in Bash

非 Y 不嫁゛ 提交于 2019-11-26 10:31:32

问题


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 interpreted. Here is an example - also creating and erasing needed files.

#!/bin/bash
f1=\"file n1\"
f2=\"file n2\"
# create files
touch \"$f1\" \"$f2\"
# concatenate arguments
args=\"\\\"$f1\\\" \\\"$f2\\\"\"
# Print arguments, then launch \'ls\' command
echo \"arguments :\" $args
ls $args
# delete files
rm \"$f1\" \"$f2\"

With that, I have some \"no such file\" errors for \"file, n1\", \"file and n2\"


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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



回答5:


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'"'


来源:https://stackoverflow.com/questions/7454526/variable-containing-multiple-args-with-quotes-in-bash

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