1

basically I am creating another SH file inside a SH file using vi editor and echo commands. here is the content of original SH file-

#!/bin/bash
echo "#!/bin/bash" > f1.sh
echo "echo "hello"" > f1.sh

f1 is the SH file I want to write into using echo commands but upon running the original file f1 file does not get #!bin/bash written into it it only has the echo "hello" command. I have tried writing the echo HASHBANG command as echo \#\!/bin/bash but that is not working as well. so how do u write #!bin/bash into another SH file using echo commands in vi editor?

  • > truncates the output file, >> appends to it. You're truncating the file on each echo, so only the text output by the last echo stays there. Also note that "echo "hello"" is the same as "echo "hello, or "echo hello", the "inner" quotes won't be there in the output. Try something like echo 'echo "hello"'. Or use a here-doc. – ilkkachu Aug 20 '21 at 11:52
  • @ilkkachu thanks I got it – lives_in_virgosupercluster Aug 20 '21 at 12:05

1 Answers1

1

Use a here-document instead:

#!/bin/bash

cat >f1.sh <<'SCRIPT_END' #!/bin/bash echo "hello" SCRIPT_END

This passes the script as it is, without the shell interfering in anything, to cat, which redirects it to the file f1.sh.

There are many issues wih your code, but the issue related to redirection is that you truncate (empty) the f1.sh file each time you use > to redirect to it. This means that the second echo in your code overwrites the data written to the file by he first echo.

Also, the quoting on the second line with echo does not make sense.

The Vi editor does not have anything to do with this.

Kusalananda
  • 333,661