简体   繁体   中英

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.

In sh and ash, it seems that I can't use the -1 .
How do I need to change the code to get it working in ash or 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.

${timeend::-1} is a bash extension (in fact a relatively recent one with negative offsets).

POSIX shell supports the following syntax :

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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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