I'm running a very simple telnet bash script and it works.

cmd2=meminfo > /tmp/top.txt

echo open ${host} ${port}
sleep 5
echo ${login}
sleep 5
echo ${passwd}
sleep 10
#echo ${cmd1}
#sleep 5
echo ${cmd2}
sleep 20
echo exit

However, the output of meminfo is not copied on "top.txt" file. The file is created

root@raspberrypi:/etc/my_scripts# ls -l /tmp/
total 12
-rw-r--r-- 1 root root 784 Oct 13 14:32 1wall_test1_S.txt
-rw-r--r-- 1 root root 216 Oct 14 11:28 test_l.txt
-rw-r--r-- 1 root root 216 Oct 14 11:37 test_s.txt
-rwxrwxrwx 1 root root   0 Oct 15 09:35 top.txt

Any suggestion?


3 Answers 3


the problem lies in

cmd2=meminfo > /tmp/top.txt

this actualy sets the variable cmd2 to meminfo and evaluates the redirection. you should quote this.

cmd2='meminfo > /tmp/top.txt'

edit: this creates the file on the target. according to your own answer you wanted to create it on the system that runs the script (not stated in your original question). the cause is still valid, but the solution is not.

  • The problem is that I have to re-direct the output command not on the local machine but on the remote machine where I'm running the script
    – Federi
    Oct 15, 2015 at 10:46
  • Yes, that is the scenario. I managed to get my output with ./telnet.sh | telnet > /tmp/top.txt I However, that command run every 5 minutes and every time it runs it overwrites the old file. How can I create and incremented file?
    – Federi
    Oct 15, 2015 at 11:15
  • easy! Thak you!
    – Federi
    Oct 15, 2015 at 18:21

Use alias cmd2="meminfo > /tmp/top.txt" to create an alias command, instead of using an environment variable called cmd2.

  • Hi Joe, thank you for your reply. How can I insert the alias in the script? Can you explain me why the variable is not good? Those are my first steps in scripting world and I would understand "why" :)Thank you
    – Federi
    Oct 15, 2015 at 10:05
  • The alias should be created after you are connected to the telnet session, and then you just add echo cmd2. Unfortunately I can't reproduce, as the open command is different on CentOS or Ubuntu, but I'll try.
    – Joe Pepto
    Oct 15, 2015 at 10:25

Found the solution by myself :)

./telnet.sh | telnet > /tmp/top.txt 

In this way I redirect the command to an output file. However, I have to run the same script many times and I don't want overwrite the same file, but I would create and incremental file (good idea would be renamed with DATE command).

to use a date option

./telnet.sh | telnet > /tmp/top-$(date +%Y%m%d-%T).txt

You must log in to answer this question.

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