I have written a shell script called "a.sh" in linux with one line:

cd ..

: and then I run this with:

chmod +x a.sh
sh ./a.sh

: how do I run this without getting :

"Command not found" or "Can't cd". Maybe I have been looking at this code too long or am I doing something obviously wrong??

Note: I have since found out what was wrong. Emacs was inserting some strange "^m" character at the end of every line

link|improve this question

69% accept rate
1  
chmod +x a.sh sh ./a.sh is not a valid command. Did you mean to show multiple lines? Also, can you paste the actual output from the command? – Stefan Lasiewski Nov 29 '10 at 18:24
Yes, sorry, I meant them to be on multiple lines. I have amended the question now – Zubair Nov 29 '10 at 18:26
1  
With regard to your note: ^M is ASCII-13, the carriage return (CR); *nix clients only use the line feed (LF, ASCII-10) character on its own. But Windows/DOS machines like to have both CRLF, resulting in ^M at the end of lines in situations where the difference is not being handled. Did you write your script in windows and then run it on linux without conversion? – Orbling Nov 29 '10 at 19:01
feedback

2 Answers

up vote 5 down vote accepted

cd is a builtin to your shell. Anything like /usr/bin/cd or /bin/cd just there for weird magical reasons.

First run this.

which sh

This will output the path to your sh executable

Try adding a shebang to your script. So the entire file looks like this

#!/bin/sh
cd ..

If that doesn't work then clarify the steps you've taken as Stefan has asked. As well as paste the exact error message.

link|improve this answer
feedback

what if you put /bin/cd in it's place.

link|improve this answer
Then I get:/bin/cd: No such file or directory – Zubair Nov 29 '10 at 18:22
2  
cd is a shell builtin. In fact it cannot be implemented as an external command, as changing the current directory within a child process wouldn't affect parent at all, and after child exits, nothing will be changed. See chdir(2). – whitequark Nov 29 '10 at 18:26
Can you explain a bit more. I don't understand what you are saying about external commands – Zubair Nov 29 '10 at 18:30
5  
External commands are programs that reside on the hard disk. When you type their name in a shell, the shell loads that program, temporarily gives control to that program, and then resumes once that program finishes. The shell that gives you the command prompt is itself a program, and it has several commands built in which are appropriately called builtins. When you type the name of a builtin, the shell itself handles it, without loading and running another program. – ultrasawblade Nov 29 '10 at 18:45
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.