Why doesn't chmod work in my bash script? Error is something about the directory...? [duplicate]
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"
.