13

I installed Ubuntu bash on my windows machine, so I can test linux scripts away from work. I created a very simple script with basic "hello world" and a change directory (cd), but when executing it displays the hello world. It errors out on the cd to directory line.

Here is the error:

$ ./test.sh
hello world
zipping away
./test.sh: line 6: cd: $'/home/fjaffer/temp\r\r': No such file or directory
./test.sh: line 7: $'\r': command not found
ffr@DP-PC:~$

My script test.sh is below:

#!/bin/bash
echo "hello world"
echo "zipping away"
dir=/home/fjaffer/temp
cd $dir

Please advise? Thank you.

αғsнιη
  • 36,350

2 Answers2

18

It's because you have created your script in a windows machine, some \r (carriage return) has been added at the end of each line.

Remove them like this:

tr -d '\r' < test.sh > new-test.sh

Also quote the variable's value:

cd "$dir"

then run your script:

./new-test.sh

As a hint it's also better to use:

 cd ... || exit

in case of any failure.


Configure your editor so it uses Linux format for saving files (If it's capable of) or use an editor in bash like nano:

enter image description here

terdon
  • 104,119
Ravexina
  • 57,256
11

Another option is to using dos2unix command to convert the file to Unix type format.

Usage:

dos2unix your_file
αғsнιη
  • 36,350