在bash中,如何存储在一个变量返回值? [英] In bash, how to store a return value in a variable?

查看:166
本文介绍了在bash中,如何存储在一个变量返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Linux中一些非常基本的命令,我试图写一些脚本。我已经写它评估了一个5位数字的最后2位数字的总和函数。该函数应串联这产生的和在过去的2位数之间,并将其返回。我想返回该值的原因是因为我将使用在其他功能这个值。

I know some very basic commands in Linux and am trying to write some scripts. I have written a function which evaluates the sum of last 2-digits in a 5-digit number. The function should concatenate this resultant sum in between the last 2-digits and return it. The reason I want to return this value is because I will be using this value in the other function.

例如:如果我有12345,那么我的函数将计算4 + 5,返回495

Ex: if I have 12345, then my function will calculate 4+5 and return 495.

#!/bin/bash

set -x
echo "enter: "
        read input

function password_formula
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        echo $second
        echo $sum

        if [ $sum -gt 9 ]
        then
               sum=${sum:1}
        fi

        value=$second$sum$first
        return $value
}
result=$(password_formula)
echo $result

我想呼应,看到的结果,但我得到的输出,如下图所示。

I am trying to echo and see the result but I am getting the output as shown below.

-bash-3.2$ ./file2.sh 
+++ password_formula
+++ echo 'enter: '
+++ read input
12385
+++ length=8
+++ last_two=85
++++ echo 85
++++ sed -e 's/\(.\)/\1 /g'
++++ awk '{print $2}'
+++ first=5
++++ echo 85
++++ sed -e 's/\(.\)/\1 /g'
++++ awk '{print $1}'
+++ second=8
+++ let sum=5+8
+++ sum_len=2
+++ echo 5
+++ echo 8
+++ echo 13
+++ '[' 13 -gt 9 ']'
+++ sum=3
+++ value=835
+++ return 835
++ result='enter: 
5
8
13'
++ echo enter: 5 8 13
enter: 5 8 13

我也试图打印结果为:

I also tried to print the result as:

password_formula
RESULT=$?
echo $RESULT

但是,这是给一些不知名的值:

But that is giving some unknown value:

++ RESULT=67
++ echo 67
67

我怎样才能正确地储存在屏幕上正确的值并打印(双重检查)?

How can I properly store the correct value and print (to double check) on the screen?

先谢谢了。

推荐答案

更改此行:

return $value

是这样的:

echo $value

然后,你可以捕捉它的输出。

Then you can capture it's output.

这篇关于在bash中,如何存储在一个变量返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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