Linux – How to echo a line of bash to file without executing

bashcommand linelinux

I'm currently trying to write a bash script from within another bash script.
I do the following:

touch /home/file.sh
echo "#!/bin/bash" >> /home/file.sh
echo "for line in $(grep -o 'guest-......' /etc/passwd | sort -u); do sudo deluser $line; done >> /home/file.sh

The problem is that echo not only writes to file but executes part of the for loop. So the file content becomes something like the following.

#!/bin/bash
for line in guest-rbrars; do sudo deluser ; done

Instead of:

#!/bin/bash
for line in $(grep -o 'guest-......' /etc/passwd | sort -u); do sudo deluser $line; done >> /var/log/cron 2>&1

How do I get to push that for loop to a file without executing part of it?

Thank you!

Best regards

Best Answer

You need to escape all the special symbols. The $ symbol is special because it represents a variable name, or a code block inside the parentheses. So if you run it, bash will try to run it first in the script that contains the writing code and then write the result to your file (/home/file.sh).

To escape a symbol, use the \ symbol. For example:

echo "for line in \$(grep -o 'guest-......' /etc/passwd | sort -u); do sudo deluser \$line; done" >> /home/file.sh
Related Question