如何在 Bash 参数中保留引号? [英] How to keep quotes in Bash arguments?

查看:34
本文介绍了如何在 Bash 参数中保留引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Bash 脚本,我想在传递的参数中保留引号.

I have a Bash script where I want to keep quotes in the arguments passed.

示例:

./test.sh this is "some test"

然后我想使用这些参数,并重新使用它们,包括整个参数列表周围的引号和引号.

then I want to use those arguments, and re-use them, including quotes and quotes around the whole argument list.

我尝试使用 "$@",但这会删除列表中的引号.

I tried using "$@", but that removes the quotes inside the list.

我该如何实现?

推荐答案

只需在带有双引号的字符串周围使用单引号:

Just use single quotes around the string with the double quotes:

./test.sh this is '"some test"'

所以单引号里面的双引号也被解释为字符串.

So the double quotes of inside the single quotes were also interpreted as string.

但我建议将整个字符串放在单引号之间:

But I would recommend to put the whole string between single quotes:

 ./test.sh 'this is "some test" '

为了理解 shell 正在做什么或者更确切地说是解释脚本中的参数,你可以写一个这样的小脚本:

In order to understand what the shell is doing or rather interpreting arguments in scripts, you can write a little script like this:

#!/bin/bash

echo $@
echo "$@"

然后你会看到并测试,用不同的字符串调用脚本时会发生什么

Then you'll see and test, what's going on when calling a script with different strings

这篇关于如何在 Bash 参数中保留引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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