为什么此bash函数仅打印整个字符串的第一个单词? [英] Why this bash function prints only first word of whole string?

查看:35
本文介绍了为什么此bash函数仅打印整个字符串的第一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建函数,该函数将以某种颜色打印绑定到变量的消息.消息变量作为此函数的参数传递.问题是我只得到第一个空格之前的文本(只有消息的第一个单词).我的脚本如下:

I'm trying to create function that will print message bound to variable in certain color. The message variable is passed as argument of this function. The problem is that I'm getting only text up to first space (only first word of message). My script looks like this:

#!/usr/bash

lbGREEN='\e[1;92m'
NC='\e[0m'

normalMessage="Everything fine"

echo_message() {

    echo -e  ${lbGREEN}$1${NC}

}

echo_message $normalMessage 

我的输出是:

Everything

推荐答案

对我来说,我不得不更改#!/bin/bash"的标题,但是显然这对您来说不是问题.

For me, I had to change the header for "#!/bin/bash", but apparently that is not the problem for you.

在回显中,您仅打印带有$ 1的第一个单词,如果将其更改为$ 2,则将打印第二个单词(参数),依此类推.

In your echo you are printing only the first word with the $1, if you change it to $2 you will print the second word (parameter) and so on.

您可以在引号内传递名称,也可以使用$ @打印所有参数.

You can pass the name inside quotes or print all the parameters with $@

解决方案1(带有$ @):

Solution 1 (with $@):

lbGREEN='\e[1;92m'
NC='\e[0m'
normalMessage="Everything fine"
echo_message() {
    echo -e  ${lbGREEN}$@${NC}
}
echo_message $normalMessage

解决方案2(带引号):

Solution 2 (with quotes):

lbGREEN='\e[1;92m'
NC='\e[0m'
normalMessage="Everything fine"
echo_message() {
    echo -e  ${lbGREEN}$1${NC}
}
echo_message "$normalMessage"

这篇关于为什么此bash函数仅打印整个字符串的第一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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