Problem with variables that receive content from a shell command

Asked

Viewed 199 times

0

I have a problem in a shell script I’m using for a test for a future task. The script is simple... I have a text file that has 2 columns with the delimiter ";". In the first column there are websites on the internet and in the second a number of 1 and 3.

The text file with the site name is called input and has the content below

www.uol.com.br;1
www.bol.com.br;2
www.google.com;3
www.globo.com;2

A second script that will read this file is what I’m having problems with. I try to store the content in a variable but some error is occurring because the variable is empty. Simply put, I’m testing directly into the shell.

file_name=dados_entrada

endereco= head -n 1 $file_name | cut -d ";" -f1 |  tail -n 1
num_ping= head -n 1 $file_name | cut -d ";" -f2 |  tail -n 1

When executing the 2 commands above, it writes on the screen the corresponding values that should be in the variable but when entering the command echo $endereco and echo $num_ping , the content is empty as excerpt below:

caio@caio-debian:~/Documentos$ echo $endereco

caio@caio-debian:~/Documentos$ echo $num_ping

caio@caio-debian:~/Documentos$

Currently I use Debian as OS.

caio@caio-debian:~/Documentos$ uname -a
Linux caio-debian 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 GNU/Linux

Would anyone know what I’m missing?

I thank you for the strength!

1 answer

0


I added operator usage $() to correctly assign the command output to the variable.

To check the variable value the command echo must be executed in the script itself, where the value assigned to the variable is still available.

file_name=dados_entrada

endereco=$(head -n 1 $file_name | cut -d ";" -f1 | tail -n 1)
num_ping=$(head -n 1 $file_name | cut -d ";" -f2 | tail -n 1)

echo $endereco 
echo $num_ping

Terminal output:

www.uol.com.br
1
  • 1

    Man, that’s right! I swear I did not miss the class of variable declaration! Thank you very much for the strength! It was right!!

Browser other questions tagged

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