Reputation: 363
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.
Upvotes: 0
Views: 225
Reputation: 74685
${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.
Upvotes: 0