Bash中包含多个带有引号的参数的变量 [英] Variable containing multiple args with quotes in Bash

查看:274
本文介绍了Bash中包含多个带有引号的参数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成一个bash变量,其中包含我的所有arg,而这些arg包含空格. 当我使用这些args启动命令时-例如ls $ args-引号未正确解释. 这是一个示例-还创建和删除所需的文件.

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"

这样,对于文件 n1" 文件 n2,我有一些没有这样的文件"错误"

推荐答案

您可以考虑使用 array 表示args,如下所示:

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

这篇关于Bash中包含多个带有引号的参数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆