如何将字符串转换为数组一个bash函数中 [英] how to convert a string into an array within a bash function

查看:184
本文介绍了如何将字符串转换为数组一个bash函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写在bash一个函数,一个空格分隔字符串,并在该字符串输出的第一个字。我试过

I am trying to write a function in bash that takes a space delimited string and outputs the 1st word in that string. I tried

function myFunc { a=$1; b=($a); echo ${b[0]};}

myStr="hello world"
myFunc myStr

我没有得到任何输出。

I get no output.

如果我在函数定义替换= $ 1上方有=世界你好,然后我得到的应用预期结果。

if I replace a=$1 in the function definition above with a="hello world", then I get the expected result on applying

myFunc

结果:你好

此外,如果强似myStr中作为参数传递我在Hello World的直接,它也可以:

Also if instead of passing myStr as an argument I pass in "hello world" directly, it also works:

myFunc "hello world"

结果:你好

我试过各种迂回与感叹号,还有 EXPR 结构,但无济于事。最后,以下似乎工作:

I tried all kinds of indirections with the exclamation points, as well as the expr constructions but to no avail. Finally the following seems to work:

function el_index { alias a=$1; b=($a); echo ${b[2]};}

我想在这里收集所有其他可能的方法来完成上述同样的事情。尤其是有办法绕过中间变量完全,并完成类似B =($ {$ A})在上面的函数体中第二条语句?顺便说一下,在施工

I would like to gather here all other possible ways to accomplish the same thing as above. In particular, is there a way to bypass the intermediate variable a completely, and do something like b=(${$a}) in the second statement within the function body above? By the way, the construction

b=($a)

分割存储在到使用默认定界符,这是一种单一的空白字的串

splits the string stored in a into words using the default delimiter, which is a single white space.

谢谢!

推荐答案

您不弄不输出 - 你得到你传递的字符串的第一个字:

You don't "get no output" -- you do get the first word of the string you passed:

function myFunc { a=$1; b=($a); echo ${b[0]}; }
myStr="hello world"
myFunc myStr

myStr

如果你传递一个变量的名称的,你要扩大间接变量在函数

If you're passing a variable name, you have to indirectly expand the variable in your function

function myFunc { a=${!1}; b=($a); echo ${b[0]}; }
# ..................^^^^^
myFunc myStr

hello


下面是另一种技术:它采用的变量名作为第一个参数,然后用文字将覆盖在值位置参数的变量。第一个字是那么第一个位置参数


Here's another technique: it takes the variable name as the first parameter, then overwrites the positional parameters with the words in the value of the variable. The first word is then the first positional parameter

firstword() { set -- ${!1}; echo $1; }
firstword myStr

hello

这篇关于如何将字符串转换为数组一个bash函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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