shell script: bad interpreter: No such file or directory when using pwd

后端 未结 11 1638
抹茶落季
抹茶落季 2021-02-07 09:30

I want to go through the files in a directory with a for loop but this comes up.

echo: bad interpreter: No such file or directory

code:

相关标签:
11条回答
  • 2021-02-07 09:50

    This issue could also occur when the file is not in unix format.. try running dos2unix againts the file and try again.

    0 讨论(0)
  • 2021-02-07 09:55

    You can find where bash is located using command

    whereis bash
    

    and you can copy the bash path to the path where you are seeing bad-interpreter error.

    0 讨论(0)
  • Better do :

    #!/bin/bash
    count=0
    dir="$PWD"
    echo "$dir"
    
    for file in "$dir"/*
    do
     if [[ -f $file ]]
     then
      ((count++))
     fi
    done
    echo $count
    

    or a simplest/shortest solution :

    #!/bin/bash
    
    echo "$PWD"
    
    for file; do
     [[ -f $file ]] && ((count++))
    done
    
    echo $count
    
    0 讨论(0)
  • 2021-02-07 10:00

    That's a strange error to be getting. I recommend trying to find the source of the error.

    One thing is to check the pwd command.

    type pwd
    

    Make sure it's /usr/bin/pwd or /bin/pwd, and verify it's not a script:

    file /usr/bin/pwd
    

    If it is a script, I bet it starts with

    #!echo
    
    0 讨论(0)
  • 2021-02-07 10:02

    I have just come across the same issue and found that my error was in my first line, having

    #!bin/bash
    

    instead of

    #!/bin/bash
    
    0 讨论(0)
  • 2021-02-07 10:04

    The echo: bad interpreter: No such file or directory is most likely coming from the first line, #!... which is called shebang line.

    About the #!... line

    This line hints the shell what interpreter to use to run the file. That can be e.g. bash, or sh (which is (roughly) a subset so a lot of things won't work), or basically anything that can execute the file content - Perl, Python, Ruby, Groovy...

    The line points the system in cases like calling the script directly when it's executable:

    ./myScript.sh
    

    It is also often used by editors to recognize the right syntax highlighting when the file has no suffix - for instance, Gedit does that.

    Solution

    To override the line, feed the script to Bash as a parameter:

    bash myScript.sh
    

    Or, you can 'source' it, which means, from within a Bash shell, do either of

    source myScript.sh
    . myScript.sh
    

    which will work (roughly) as if you pasted the commands yourself.

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