undefine
undefine

Reputation: 142

put output from command into many variables in sh

I have command, which output two columns. For example:

undefine@uml:~$ uptime -s
2015-10-26 08:47:12

How can i put this two columns into separate variables? I would like to do something like:

undefine@uml:~$ uptime -s | read day hour
undefine@uml:~$ echo $day
undefine@aml:~$

I know, that in bash i can execute it like:

undefine@uml:~$ read day hour <<< $(uptime -s)
undefine@uml:~$ echo $day
2015-10-26

I can also redirect output from uptime to file, and then read from that file:

undefine@uml:~$ uptime -s > tmpfile
undefine@uml:~$ read day hour < tmpfile
undefine@uml:~$ echo $day
2015-10-26

But how to do it "posix sh way", and without creating any temporary files?

Upvotes: 0

Views: 130

Answers (3)

CheesyMacHack
CheesyMacHack

Reputation: 15

You could split it by piping to cut like so

myVar1=$(echo uptime -s | cut -d" " -f1)
myVar2=$(echo uptime -s | cut -d" " -f2)

This normally works for bash. On sh you would have to use back ticks so

myVar1=`uptime -s | cut -d" " -f1`
myVar2=`uptime -s | cut -d" " -f2`

Hope this helps

Upvotes: -1

sjnarv
sjnarv

Reputation: 2384

If you don't care about the two assigned variables being named $1 and $2, you could use:

set $(uptime -s)

(This is not a completely serious answer.)

Upvotes: 2

chepner
chepner

Reputation: 532043

In POSIX shell, you can a here document along with command substitution:

read day hour <<EOF
$(uptime -s)
EOF

(Technically, this may still use a temporary file, but the shell manages it for you.)

Upvotes: 1

Related Questions