ai didi

linux - Bash 将变量作为带引号的参数传递

转载 作者:太空狗 更新时间:2023-10-29 12:12:08 24 4
gpt4 key购买 nike

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

$ ./program "Hello there"
Hello there

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

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

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

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

是否可以让 bash 将引号视为我自己在第一个代码块中输入的引号?

最佳答案

我不知道你从哪里得到程序,但看起来它坏了。这是用 bash 编写的正确方法:

#!/bin/bash

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

这会将每个参数打印在单独的一行中,以便于区分它们(当然对于包含换行符的参数会有问题,但我们不会传递这样的参数)。

将以上内容保存为程序并赋予其执行权限后,试试这个:

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

鉴于

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

关于linux - Bash 将变量作为带引号的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39583838/

24 4 0
文章推荐: jquery - CSS3 渐变和背景图片
文章推荐: html - 垂直对齐永远行不通
文章推荐: css - Helvetica CSS 字体引述
文章推荐: javascript - 使用 Dropzone.js 的非 ajax 帖子
太空狗
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com