Bash传递变量作为带引号的参数 [英] Bash pass variable as argument with quotes

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

问题描述

假设./program是一个仅打印出参数的程序;

Assume ./program is a program that just prints out the parameters;

$ ./program "Hello there"
Hello there

如何正确地传递变量中带引号的参数?我正在尝试这样做;

How can I properly pass arguments with quotes in from a variable? I am trying to do this;

$ args='"Hello there"'  
$ echo ${args}  
"Hello there"  
$ ./program ${args}  
Hello there # This is 1 argument

但是,当我通过一个变量时,args中的引号似乎被忽略了,所以我得到了;

but instead, when I go through a variable the quotes in args seem to be ignored so I get;

$ args='"Hello there"'
$ echo ${args}
"Hello there"
$ ./program ${args}
"Hello there" # This is 2 arguments

是否可以让bash对待引号,就像我自己在第一个代码块中输入引号一样?

Is it possible to have bash treat the quotes as if I entered them myself in the first code block?

推荐答案

我不知道您从何处获得program,但看来它已经坏了.这是用bash编写的正确方法:

I don't know where you got program from, but it appears that it's broken. Here's a correct way to write it in bash:

#!/bin/bash

for arg in "$@"; do
    echo "$arg"
done

这会将每个参数打印在单独的行中,以使它们更易于区分(当然,包含换行符的参数会出现问题,但我们不会传递此类参数).

This will print each argument in a separate line to make them easier to distinguish (it will of course have a problem with arguments that contain a line break, but we will not pass such an argument).

将以上内容另存为program并授予其执行权限后,请尝试以下操作:

After you have saved the above as program and gave it the execute permission, try this:

$ args='"Hello there"'
$ ./program "${args}"
"Hello there"

$ args='"Hello there"'
$ ./program ${args}
"Hello
there"

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

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