简体   繁体   English

Shell脚本中变量的范围

[英]scope of variables in shell script

I am new to shell scripting. 我是Shell脚本的新手。 My aim is to print the numbers like 01, 02, 03...09 if the user enters 1,2,3,4...9 (less than 10). 我的目标是,如果用户输入1,2,3,4 ... 9(小于10),则将数字打印为01、02、03 ... 09。 I wrote the below code but lst line print the value is of only single digit. 我写了下面的代码,但第一行打印的值只有一位数字。

issuehour()
{
  issue_hour="$1";

  if [ $issue_hour -lt 10 ] then 
    h="0"$issue_hour
    return $h
  else
    #echo "less than 10"
    return "$1"
  fi
}

echo "enter hour"
read hour
hr=$(issuehour "$hour")
echo "after calling function:-" $hr

Return statement in bash is synonymous to exit code and ranges from 0 - 255. bash中的return语句与退出代码同义 ,范围为0-255。

"Echo" is used to return value / output the value of the function. “回声”用于返回值/输出函数的值。 This should be captured by the calling function using $( ) similar to hr=$(issuehour "$hour") that you have used. 这应该由调用函数使用$( )捕获,类似于您使用的hr=$(issuehour "$hour")

Coming to your question, without the echo statement, the function did not return any value to the calling function and that explains why you did not get the desired output. 关于您的问题,没有echo语句,该函数未向调用函数返回任何值,这说明了为什么未获得所需的输出。 However, since you have used "return", that would have been considered as the ' return code of the function '. 但是,由于使用了“ return”,因此将其视为“ 函数返回代码 ”。 To verify this, try: 要验证这一点,请尝试:

function issuehour()
{
  issue_hour="$1";

  if [[ $issue_hour -lt 10 ]]
  then
    h="0"$issue_hour
    return $h
  else
    #echo "less than 10"
    return "$1"
  fi
}

echo "enter hour"
read hour
hr=$(issuehour "$hour")
echo $?

This will give the same result you were looking for. 这将提供与您想要的结果相同的结果。

PS: It is better to follow the conventional method of using "echo" to return value of the function and "return" statement for "return code" PS:最好遵循使用“ echo”返回函数值和“ return”语句作为“ return code”的常规方法。

Just use printf with 0 padding: 只需使用带有0填充的printf

printf "%02d\n" 1
01
printf "%02d\n" 2
02
printf "%02d\n" 9
09
printf "%02d\n" 10
10

You can use the following code. 您可以使用以下代码。

issuehour()
{
  issue_hour="$1";

  if [ $issue_hour -lt 10 ] ;then
    h="0"$issue_hour
    echo $h
  else
    #echo "less than 10"
    echo "$1"
  fi
}

echo "enter hour"
read hour
hr=$(issuehour "$hour")
echo "after calling function:-" $hr

return command will return the exit status of a function , Instead you can use echo command. return命令将返回函数的退出状态,而可以使用echo命令。

[root@server1 tmp]# bash new
enter hour
10
after calling function:- 10
[root@server1 tmp]# bash new
enter hour
1
after calling function:- 01

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

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