Skip to content

Instantly share code, notes, and snippets.

@lhns
Last active October 10, 2020 14:44
Show Gist options
  • Save lhns/00ccf1d14363411e0917bc1a8fad67e6 to your computer and use it in GitHub Desktop.
Save lhns/00ccf1d14363411e0917bc1a8fad67e6 to your computer and use it in GitHub Desktop.
:: Remove the error message produced by a shebang in a batch script
#!/bin/sh
@ 2>/dev/null # 2>nul & echo off & goto :BOF
:BOF
:: Remove shebang error message
setlocal EnableDelayedExpansion
:: Exclamation mark would be stripped
set "SHEBANG=#./bin/sh"
:: Get console width
set "CONSOLE_WIDTH="
set /a LINECOUNT=0
for /f "tokens=1,2,*" %%A in ('mode con') do (
set /a LINECOUNT+=1
if !LINECOUNT!==4 set CONSOLE_WIDTH=%%B
)
:: Get CR and BS characters
for /f %%A in ('copy /z "%~dpf0" nul') do set "CR=%%A"
for /f %%A in ('"prompt $H & for %%B in (0) do rem"') do set "BS=%%A"
set "BLANK="
:: Simulate error message (could be localized)
for /f "tokens=* USEBACKQ" %%A in (`cmd /c "%SHEBANG% 2>&1"`) do (
:: Calculate string length
set "ELEM=%%A "
set /a STRING_LENGTH=0
for %%I in (512 256 128 64 32 16 8 4 2 1) do if not [!ELEM:~%%I!]==[] (
set /a STRING_LENGTH+=%%I
set "ELEM=!ELEM:~%%I!"
)
:: Calculate soft line breaks
for /l %%I in (1,!CONSOLE_WIDTH!,!STRING_LENGTH!) do (
:: Calculate line length
set /a LINE_LENGTH=!CONSOLE_WIDTH!
if !STRING_LENGTH! LSS !CONSOLE_WIDTH! set /a LINE_LENGTH=!STRING_LENGTH!
set /a STRING_LENGTH-=!CONSOLE_WIDTH!
:: Construct blanking line
set "BLANK_LINE="
for /l %%I in (1,20,!LINE_LENGTH!) do if !LINE_LENGTH! GEQ 20 (
set /a LINE_LENGTH-=20
set "BLANK_LINE=!BLANK_LINE! "
)
for /l %%I in (1,1,!LINE_LENGTH!) do set "BLANK_LINE=!BLANK_LINE! "
set "BLANK=!BS!!CR!!BLANK_LINE!!CR!!BLANK!"
)
)
:: Print blanking string
<nul set /p "=!BLANK!" 1>&2
endlocal
echo test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment