'\r' added end of the script command

This is my script:

#!/bin/bash
hd='pwd'
cd $hd

When I try to run it, it fails with:

line 3: cd: $'pwd\r\r': No such file or directory

What is going on?


The \r issue suggests you have edited the script file on a Windows machine. Windows uses \r\n as the line terminator while Linux (and most other operating systems) use \n alone. When you edit a file in Windows, Windows will add \r to the end of the lines and that will break your scripts.

So, first remove the \r:

sed -i 's/\r//g' script.sh

The next issue is that your script isn't doing what you think it is. Or what I imagine you think it is, since you didn't actually say. I am guessing that you think that hd='pwd' sets the variable $hd to the value returned by the command pwd. That isn't what's happening. You are simply setting the variable to the string pwd:

$ hd='pwd'
$ echo "$hd"
pwd

To use the output of a command as the value for a variable, you need to use var=$(command) or var=`command`:

$ hd=$(pwd)
$ echo $hd
/home/terdon

So your script should be:

#!/bin/bash
hd=$(pwd)
cd "$hd"

In this case, however, you don't even need that. The current directory is already in a variable:

$ echo "$PWD"
/home/terdon

So you could also have done hd=$PWD. Or simply cd "$PWD".