简体   繁体   English

在 Bash 中为所有数组元素添加前缀

[英]Adding a prefix to all array elements in Bash

I am storing command line parameters in an array variable.我将命令行参数存储在数组变量中。 (This is necessary for me). (这对我来说是必要的)。 I wanted to prefix all the array values with a string passing through a variable.我想用一个通过变量的字符串作为所有数组值的前缀。

PREFIX="rajiv"

services=$( echo $* | tr -d '/' )

echo  "${services[@]/#/$PREFIX-}"

I am getting this output.我得到这个输出。

> ./script.sh webserver wistudio
rajiv-webserver wistudio

But I am expecting this output.但我期待这个输出。

rajiv-webserver rajiv-wistudio

Your array initialization is wrong.你的数组初始化是错误的。 Change it to this:改成这样:

services=($(echo $* | tr -d '/'))

Without the outer () , services would become a string and the parameter expansion "${services[@]/#/$PREFIX-}" adds $PREFIX- to your string.如果没有外部()services将成为一个字符串,参数扩展"${services[@]/#/$PREFIX-}"$PREFIX-添加到您的字符串中。

In situations like this, declare -p can be used to examine the contents of your variable.在这种情况下, declare -p可用于检查变量的内容。 In this case, declare -p services should show you:在这种情况下, declare -p services应该显示:

declare -a services=([0]="webserver" [1]="wistudio") # it is an array!

and not并不是

declare -- services="webserver wistudio"             # it is a plain string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM