How to print #!/bin/bash using echo command

10,295

Solution 1

! is magic in a default interactive bash session, but not in scripts (set +H to disable in an interactive prompt). In any case:

echo '#!/bin/bash'

Solution 2

Or with no quotes and escaping the # and the !:

echo \#\!/bin/bash

Solution 3

printf should work too:

printf '#!/bin/bash\n'
Share:
10,295
Seff
Author by

Seff

Updated on June 04, 2022

Comments

  • Seff
    Seff about 2 years

    I have tried the escape character but it doesn't seems works with !. I need this to auto-configure packages using scripts.

  • fedorqui
    fedorqui about 10 years
    That is, using single quotes you avoid variable expansion.
  • Adam H. Peterson
    Adam H. Peterson about 10 years
    printf is beside the point. The issue is the shell's interpreting of the hashmark, not which command it's passed to. (Also, if you're going to use printf, you'll want to include a \n at the end, or your shebang line will run into the next line printed.
  • Adam H. Peterson
    Adam H. Peterson about 10 years
    (Correction: I meant bang, rather than hashmark.)
  • Avi Das
    Avi Das about 10 years
    Whoops you are right, it does need the \n
  • ElmoVanKielmo
    ElmoVanKielmo about 10 years
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
  • Reinstate Monica Please
    Reinstate Monica Please about 10 years
    @ElmoVanKielmo It does provide an answer to the question, though the issue OP was having wasn't really related to echo/printf so it's basically the same as that other guy's
  • ElmoVanKielmo
    ElmoVanKielmo about 10 years
    @BroSlow this was a review and as you probably know - messages are predefined in that case.