Skip to content
Advertisement

How can I ingore whitespaces inside an echo command when usual methods don’t seem to work

Hi I’m pretty new to linux/bash in general and I’m having a some trouble making a script for my coworker. Idea of this script is to help automate coworkers IP table entries (don’t use IP tables myself so no idea how it works, just working as per his instructions). Program is going to ask a few questions, form an entry and then add it to a file on a different host. After the file is written it will also run “systemctl reload iptables.service” and “systemctl status iptables”. I tested that pwd was atleast working where I was planning to put these.

The code worked fine with a single word in place of table_entry variable, I was able to write something to a file in my host computer with a different user.

Problem is that the “table_entry” variable is going to have whitespaces in it and the sudo su -c command gets the second word as input (atleast that’s what I think is happening) and I get an error sudo: INPUT: command not found. the “INPUT” coming from my case sentence

I tried to put the “table_entry” variable in “{$table_entry}” , “$table_entry” and {$table_entry} forms but they didn’t work.

I removed some of the code to make it more readable (mostly case sentences for variables and asking for host and username).

#!/bin/bash
echo -e "Which ports?
1. INPUT
2. OUTPUT
3. Forward"
read opt_ch

case $opt_ch in
 1) chain="INPUT" ;;
 2) chain="OUTPUT" ;;
 3) chain="FORWARD" ;;
 *) echo -e "Wrong Option Selected!!!"
esac

table_entry="-A $chain "#-s $ip_source -d $ip_dest

ssh -t user@host "sudo table_entry=$table_entry su -c 'echo $table_entry >> /home/user/y.txt'"
                  #^ this line will later also include the systemctl commands separated with ";" ^

I tested few different methods how to do this script overall, heredoc(didn’t get input to work very well), Ansible(Didn’t really seem like a great tool for this job), Python(can’t install new modules to the enviroment). So this is the best solution I came up with bearing my limited skillset.

Edit: I also realise this is propably not the smartest way to do this script, but it’s the only one I have gotten to work this far, that can also ask for a password from the user when doing su command. I’m not knowledgeable in transferring passwords safely in linux enviroment or in general, so I like to let linux handle the passwords for me.

Advertisement

Answer

This a problem with dealing with nested quoting – which is really quite the annoying problem to solve.

This case seems like you could do this with quotes inside the string – your example would become

ssh -t user@host "sudo table_entry='$table_entry' su -c 'echo "$table_entry" >> /home/user/y.txt'"

It seems to me the table_entry='$table_entry' is redundant though, this should work:

ssh -t user@host "sudo su -c 'echo "$table_entry" >> /home/user/y.txt'"
Advertisement