0

I have a shell script that runs like this on my Ubuntu 12.04 LTS server:

cd /var/www/srv

But, for some reason, when I run it, it says: ./start.sh: 1: cd: can't cd to /var/www/srv

The directory exists, and it is run as root so no question of privileges. To add to the peculiarity, when I run the code in the terminal, it works.

nquincampoix
  • 508
  • 1
  • 4
  • 17
Daniyaal Khan
  • 285
  • 1
  • 4
  • 12
  • How do you know it is running as root? What are the ownership and permissions of that directory? Does this work with some other directory? What are the actual contents of your script? Note that changing the directory within a script will have no lasting effect after the shell interpreting that script exits. – Chris Stratton Apr 08 '14 at 18:31
  • @ChrisStratton Well, because I am running it as root. www-data is the owner of the directory. And yes, I know that the shell script will not have any effect on the terminal but, my intrest is in why can I not cd to the error. – Daniyaal Khan Apr 08 '14 at 18:38
  • Post the contents of your script and the **actual** ownership and permissions of the directory such as provided by ls -l – Chris Stratton Apr 08 '14 at 18:57

1 Answers1

3

This is a classic carriage return issue, caused by creating a shell script in a Windows/DOS editor.

Your problem:

$ cat start.sh
cd /

$ ./start.sh
cd: 1: can't cd to /

Your diagnosis:

$ cat -v start.sh
cd /^M

$ shellcheck start.sh
In start.sh line 1:
cd /
    ^-- SC1017: Literal carriage return. Run script through tr -d '\r' .

Your fix:

$ tr -d '\r' < start.sh  > fixed.sh
$ chmod +x fixed.sh
$ ./fixed.sh
(no errors)
that other guy
  • 116,971
  • 11
  • 170
  • 194