Linux – How to execute a command within a bash script

bashlinux

I am writing a script that will continuously broadcast some data to port 30000, so a python udp listener can get the data and insert it into a table, from which I can draw that information and display on a web page.

So, I want to execute

echo -n -e "\x00\x00\x0A\x00 1 012601234512345\x00" | nc -w1 -u localhost 3000

in the bash script in a while loop.

This is the bash script I have so far:

#!/bin/bash
echo 'Running Script'   
a=0  
x=1
while [ $a -le 1 ]
do
  echo 'echo -n -e "\x00\x00\x0A\x00        1      012601234'$x'12345\x00" | nc -w1 -u localhost 30000'
  sleep 5 
  let x=$(($x + 1))
done

The x variable is incrementing each time throughout the loop so the data changes each time.

At the moment I am thinking that rather than outputing that as a command to the terminal, it is just coming out as a string. I am very new to bash, and any help would be greatly appreciated.

Best Answer

You're overthinking it.

Just put the command you want to execute there, without quoting it or echoing it. Replace the variable with ${x}. Variables will be substituted in double-quoted strings, and the {} is there to make sure that your variable is interpreted as x and not x12345.

#!/bin/bash
echo 'Running Script'   
a=0  
x=1
while [ $a -le 1 ]
do
  echo -n -e "\x00\x00\x0A\x00        1      012601234${x}12345\x00" | nc -w1 -u localhost 30000
  sleep 5 
  let x=$(($x + 1))
done
Related Question