[SOLVED] Bash: Assign output of a command to a variable
Linux - SoftwareThis forum is for Software issues.
Having a problem installing a new program? Want to know which application is best for the job? Post your question in this forum.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Panic over guys and gals - I have real trouble with bash, don't use it ofetn enough but I finally figured out this, use a function
Code:
seconds(){
# calculates no of second from time in any format
# usage Example: echo $(seconds 1:01) will return 61
echo $1 | sed -E 's/(.*):(.+):(.+)/\1*3600+\2*60+\3/;s/(.+):(.+)/\1*60+\2/' | bc
}
And also there is no need to use any external command, bash can do it:
Code:
VAR="1:01"
A=(${VAR//:/ })
[[ ${#A[@]} -eq 3 ]] && sec=$((${A[0]}*3600 + ${A[1]}*60 + ${A[2]}))
[[ ${#A[@]} -eq 2 ]] && sec=$((${A[0]}*60 + ${A[1]}))
echo $sec # if you wish
# but you can use the variable sec in your script without this echo
And also there is no need to use any external command, bash can do it:
Code:
VAR="1:01"
A=(${VAR//:/ })
[[ ${#A[@]} -eq 3 ]] && sec=$((${A[0]}*3600 + ${A[1]}*60 + ${A[2]}))
[[ ${#A[@]} -eq 2 ]] && sec=$((${A[0]}*60 + ${A[1]}))
echo $sec # if you wish
# but you can use the variable sec in your script without this echo
Neat, cheers!
BTW I've used your first example!
But I've changed back to sed, I don't want to put in the hours every time.
Especially bash stumbles over its misfeature to interpret numbers with leading zero as octal; 08 or 09 gives an error in arithmetic context.
A work-around is to prefix it with 10#
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.