-1

we set the variable with the follwing values

MY_VAR=" one two three four"

how to capture the first value from variable with bash? ( without using echo command )

expected output

one

0

2 Answers 2

0

This is more appropriate for StackOverflow... in fact it's been asked many times before!

Inspiration from this answer.

$ MY_VAR=" one two three four"
$ read -ra MY_VAR <<< "${MY_VAR}"
$ echo ${MY_VAR[0]}
one
$ echo ${MY_VAR[2]}
three

Or (from this answer):

$ MY_VAR=" one two three four"
$ MY_VAR=(${MY_VAR// / })
$ echo ${MY_VAR[0]}
one
3
  • Other ways to capture expected output output=$(printf $MY_VAR) output=$(cut -d' ' -f2 <<<"$MY_VAR")
    – Paulo
    Jan 18, 2018 at 11:30
  • Both of which invoke external processes.
    – Attie
    Jan 18, 2018 at 13:14
  • I don't have defense for cut, but printf can be invoked as builtin output=$(builtin printf $MY_VAR)
    – Paulo
    Jan 18, 2018 at 15:03
0

This should work:

echo $MY_VAR | awk '{print $1;}'
1
  • without to use echo command
    – yael
    Jan 18, 2018 at 10:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .