centos - Bash error while running script

26
2014-06
  • user3524823

    I have a CentOS 6.5 64-bit dedicated server. The only thing I done on it is yum install java7, so I have not installed any other stuff.

    So in the directory /root I made this file (test.sh)

    #!/bin/bash
    while true
    do
        echo "Hey"
            echo "You have five seconds to do 'Ctrl+C' or the while loop will continue."
        sleep 5
    done
    

    I know theres nothing wrong with the code, because I have tried some other (From official websites) and I get the same errors.

    So If I do:

    cd /root
    bash test.sh
    

    I get this error

    test.sh: line 7: syntax error near unexpected token `done'
    test.sh: line 7: `done'
    

    If I do

    cd /root
    ./test.sh
    

    I get this error

    -bash: ./test.sh: Permission denied
    

    I have also tried doing this in the directory /home and I get the same errors.

    PS. I'm logged in as root via SSH.

  • Answers
  • slhck

    Fixing Permissions

    Fairly sure that the script is not executable. For that, you need to set the executable flag for the current user by running:

    chmod u+x /root/test.sh
    

    Then you should be able to run it as:

    cd /root
    ./test.sh
    

    That is, if you're currently running as root (check with whoami).

    If you want the script to be executable by another user on the system, it needs to be chmod og+x ("others and group exetuable"), however that won't work if the script itself is saved under /root, which isn't readable by other users than root itself.

    Fixing Copy-Paste Errors

    It seems from your /bin/bash^M error message that you have a Windows CRLF line ending there (\r\n), which should just be a Linux newline (\n).

    To remove this, you can run the following on the file:

    sed -i 's/\r//' test.sh
    

    Or this:

    dos2unix test.sh
    

  • Related Question

    linux - Bash Script Exits su or ssh Session Rather than Script
  • Russ Bradberry

    I am using CentOS 5.4. I created a bash script that does some checking before running any commands. If the check fails, it will simply exit 0. The problem I am having is that on our server, the script will exit the su or ssh session when the exit 0 is called.

    #!/bin/bash
    # check if directory has contents and exit if none
    if [ -z "`ls /ebs_raid/import/*.txt 2>/dev/null`" ]; then
      echo "ok"
      exit 0
    fi
    

    here is the output:

    [root@ip-10-251-86-31 ebs_raid]# . test.sh 
    ok
    [russ@ip-10-251-86-31 ebs_raid]$
    

    as you can see, I was removed from my sudo session, if I wasn't in the sudo session, it would have logged me out of my ssh session. I am not sure what I am doing wrong here or where to start.


  • Related Answers
  • pgs

    When you use . to run a shell script it executes in the current shell rather than starting a new shell. Type bash test.sh to get the behaviour you want.