How to pass command result to a bash variable?

Asked

Viewed 205 times

1

I have the following command:

cat frutas.txt | tail -n 1 | cut -d: -f 1

This command returns an integer to the terminal. How do I send this value to a variable? I tried something like this:

resl=cat frutas.txt | tail -n 1 | cut -d: -f 1

But it was a mistake:

-bash: . /fruit.txt: Permission denied

Contents of the file fruta.txt:

1:cereja:223
2:maça:23

2 answers

2

Another way is to use awk as well

resl=$(awk -F: '{print $1,$2,$3}' frutas.txt) #-F: determina que o separador seja ':'

And to pick up specific lines:

resl=$(awk -F: '{if(NR==1)print $1,$2,$3}' frutas.txt) #NR é referente ao número da linha

0


Just use the syntax of Command Substitution, which can be done in two ways.

You can put the command between `:

resl=`cat frutas.txt | tail -n 1 | cut -d: -f 1`

Or you can put the command between $():

resl=$(cat frutas.txt | tail -n 1 | cut -d: -f 1)

With this, the output of the command will be placed in the variable resl. If you want to see your value, do it:

echo $resl

In this case the result is the same in both cases, but there are situations where there may be differences between approaches. For more details about the differences, see this answer, in particular the article linked, which explains why $() is the most recommended.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.