How can I configure bash to handle CRLF shell scripts?

前端 未结 2 1955
萌比男神i
萌比男神i 2020-12-20 12:47

I want to execute bash scripts that happen to use Windows/CRLF line endings.

I know of the tofrodos package, and how to fromdos files, but if possible,

相关标签:
2条回答
  • 2020-12-20 13:35

    Perhaps like this?

    dos2unix < script.sh|bash -s
    

    EDIT: As pointed out in the comments this is the better option, since it allows the script to read from stdin by running dos2unix and not bash in a subshell:

    bash <(dos2unix < script.sh)
    
    0 讨论(0)
  • 2020-12-20 13:40

    Here's a transparent workaround for you:

    cat > $'/bin/bash\r' << "EOF"
    #!/bin/bash
    script=$1
    shift
    exec bash <(tr -d '\r' < "$script") "$@"
    EOF
    

    This gets rid of the problem once and for all by allowing you to execute all your system's Windows CRLF scripts as if they used UNIX eol (with ./yourscript), rather than having to specify it for each particular invocation. (beware though: bash yourscript or source yourscript will still fail).

    It works because DOS style files, from a UNIX point of view, specify the interpretter as "/bin/bash^M". We override that file to strip the carriage returns from the script and run actual bash on the result.

    You can do the same for different interpretters like /bin/sh if you want.

    0 讨论(0)
提交回复
热议问题