通过shell变量传递包含空格的参数 [英] Pass parameters that contain whitespaces via shell variable

查看:1082
本文介绍了通过shell变量传递包含空格的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要通过传递来自shell变量的参数来调用的程序.在整个问题中,我将假定它是由

I've got a program that I want to call by passing parameters from a shell variable. Throughout this question, I am going to assume that it is given by

#!/bin/sh
echo $#

即它打印出传递给它的参数数量.我们称之为count-args.

i.e. that it prints out the number of arguments that are passed to it. Let's call it count-args.

我这样调用程序:

X="arg1 arg2"
count-args $X

这很好.但是现在我的一个论点中有一个空格,我找不到逃脱它的方法,例如以下内容不起作用:

This works quite well. But now one of my arguments has a whitespace in it and I can't find a way to escape it, e.g. the following things do not work:

X="Hello\ World"
X="Hello\\ World"
X="'Hello World'"

在所有情况下,我的程序count-args都会打印出2.我想找到一种方法,使我可以传递字符串Hello World,并返回1.怎么样?

In all of the cases, my program count-args prints out 2. I want to find a way so I can pass the string Hello World and that it returns 1 instead. How?

仅作说明:我不想将所有参数都作为单个字符串传递,例如

Just for clarification: I do not want to pass all parameters as a single string, e.g.

X="Hello World"
count-args $X

应打印出2.我想要一种传递包含空格的参数的方法.

should print out 2. I want a way to pass parameters that contain whitespaces.

推荐答案

使用数组存储多个包含空格的参数.

Use an array to store multiple, space-containing arguments.

$ args=("first one" "second one")
$ count-args "${args[@]}"
2

这篇关于通过shell变量传递包含空格的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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