0
echo "#!/bin/bash\nls -l /home/" > /home/myscript.sh
bash: !/bin/bash\nls: event not found

My script should be:

#!/bin/bash
ls -l /home/

Why does it ignore the echo "" string and think that there is some sort of event? Why does it not recognize #!/bin/bash as a special word?

the same thing happens when I

echo "#!/bin/bash" > /home/myscript.sh

so it's not the new line!

echo -e "#\!/bin/bash" > /home/myscript.sh

writes the file content as:

#\!/bin/bash

Why is this simple action going miserably wrong?

Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66

2 Answers2

0

From the bash manpage:

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.

So either use single quotes, or disable history expansion with set +o history.

But don't use echo. Instead, do :

printf '%s\n' '#!/bin/bash' 'ls -l /home/' > /home/myscript

or

cat > /home/myscript << 'EOF'
#!/bin/bash
ls -l /home/
EOF
William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

echo -e '#!/bin/bash\nls -l /home/' > /home/myscript.sh

a combination of -e and using single quote fixed it.

Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66