简体   繁体   English

更改代码以使其在sh或ash中工作

[英]Change code to get it working in sh or ash

I wrote a function to read the time from a config file and calculate it to seconds. 我编写了一个函数来从配置文件中读取时间并将其计算为秒。

The line in the config file looks like that: 配置文件中的行如下所示:

timeend=30h

The function was written in for bash, but in the Linux Distro I use there's no bash avalaible, only sh and ash. 该函数是为bash编写的,但是在Linux Distro中,我没有bash可用,只有sh和ash。

In sh and ash, it seems that I can't use the -1 . 在sh和ash中,看来我不能使用-1
How do I need to change the code to get it working in ash or sh? 我如何更改代码以使其在ash或sh中工作?

getTimeEndFromConfig(){
case $timeend in
*s )
echo ${timeend::-1};;
*m )
zeit=${timeend::-1}
TIMEEND=$(($zeit*60))
echo ${TIMEEND};;
*h )
zeit=${timeend::-1}
TIMEEND=$(($zeit*3600))
echo ${TIMEEND};;
esac
}

Update 更新资料
So I changed it, but now I always get an arithmetic syntax error when I call the funtion. 因此,我对其进行了更改,但是现在我在调用该函数时总是遇到arithmetic syntax error

${timeend::-1} is a bash extension (in fact a relatively recent one with negative offsets). ${timeend::-1}是bash扩展名(实际上是相对较新的负偏移量)。

POSIX shell supports the following syntax : POSIX shell支持以下语法

zeit=${timeend%?}

In this context, ? 在这种情况下, ? means any character and the % means remove the shortest occurrence of the pattern from the end of the string. 表示任何字符, %表示从字符串末尾删除最短出现的模式。

Alternatively, you could use sed: 或者,您可以使用sed:

zeit=$(printf '%s' "$timeend" | sed 's/.$//')

This also removes the last character from the string. 这也会从字符串中删除最后一个字符。

In older shells that doesn't support the arithmetic expansion, I'd suggest going with awk: 在不支持算术扩展的旧Shell中,建议使用awk:

echo "$(printf '%d' "${timeend%?}" | awk '{print $1 * 3600 }')"

Here I combined the substring extraction and the multiplication in the final branch of your case statement. 在这里,我在您的case语句的最后一个分支中组合了子字符串提取和乘法。

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

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