0

I am trying to take output of an command into array and for this tried following:

#!/bin/sh

cmd=($(date +%s;sleep 5; date +%s))
start_time=$cmd[0]
end_time=$cmd[1]
echo $start_time

#EOF

I was expection echo $start_time to give me start time but it print the following:

1572443382 1572443386[0]

Can't switch to bash shell and have only access to sh

2
  • But what I would like to have output to be stored in array for both date commands and for some reasons bash/ksh can't be used. Commented Oct 30, 2019 at 14:01
  • Since you cannot use bash please don't tag the question as bash. I removed the tag for you. Commented Oct 30, 2019 at 14:21

3 Answers 3

5

Plain sh has no arrays. You have to cope without arrays. In your case that's easy:

start=$(date +%s)
sleep 5
end=$(date +%s)

echo "start=$start end=$end"

If you really, really want to have everything in one subshell then you have to store the output as a plain string and parse that string to retrieve the individual values. You can think of that one string as an "array" where each line is an array entry. Individual lines can be retrieved using sed (which uses indices starting from 1 instead of 0).

times=$(date +%s; sleep 5; date +%s)

echo "start=$(echo "$times" | sed -n 1p) end=$(echo "$times" | sed -n 2p)"

To store individual lines in variables use subshells:

times=$(date +%s; sleep 5; date +%s)
start=$(echo "$times" | sed -n 1p)
end=$(echo "$times" | sed -n 2p)

echo "start=$start end=$end"

However, if you just want to compute how long sleep 5 took you might as well use time sleep 5 which already does that for you.

Sign up to request clarification or add additional context in comments.

Comments

2

The positional parameters are the closest thing sh has to an array:

sh-3.2$ set -- "$(date +%s)"; sleep 5; set -- "$@" "$(date +%s)"
sh-3.2$ start=$1 end=$2; echo "$start -> $end"
1572448562 -> 1572448567

1 Comment

Good idea! In this case you can assign both parameters in one command just how OP wanted: set -- $(date +%s; sleep 5; date +%s); echo "$1 -> $2". Your solution can even be used without mangling the original positional parameters: set -- $(...) "$@"; ...; shift 2 # everything is back to normal.
-1

You need to use ${array[index]} syntax to access array elements. So, change your start_time and end_time to as follows.

start_time=${cmd[0]}
end_time=${cmd[1]}

Also change

#!/bin/sh to #!/bin/bash

2 Comments

I mentioned in the comments, I can't use bash for some reason, all I can use is sh
Yes, if /bin/sh is actually a link to a shell that supports arrays, which by definition is something you can't rely on. Not all Linux distributions use bash as its POSIX-compliant shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.