Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"cd" does not work in shell script

Tags:

linux

shell

cd

I am wondering why cd does not work in shell script. It is as follows,

#!/bin/sh cd test mkdir $(date +%d-%mm-%Y) 

When I run this, I get can't cd to test

cd: 2: can't cd to /test 

Why is it like this?

like image 890
Abhishek Avatar asked Feb 07 '11 05:02

Abhishek


People also ask

Can you use cd in shell script?

The cd command, also known as chdir (change directory), is a command-line shell command used to change the current working directory in various operating systems. It can be used in shell scripts and batch files.

How do I make a cd in bash?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

How do I change directory in bash script?

when you write "p" on the command line, it will change the directory. Show activity on this post. If you run a bash script then it will operates on its current environment or on those of its children, never on the parent.

What is $() in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.


2 Answers

I had the same problem. Turned out the problem was \r\n line endings.

To fix it, do

tr -d "\r" < oldname.sh > newname.sh 

From http://talk.maemo.org/showthread.php?s=1cadd53b369d5408c2b9d53580a32dc4&t=67836&page=2

like image 191
Benito Ciaro Avatar answered Sep 18 '22 23:09

Benito Ciaro


Not really relevant for this question. I had the same error message, however, I was using

cd ~/foo/bar 

After changing this to

cd $HOME/foo/bar 

it was fixed.

like image 36
Martijn Courteaux Avatar answered Sep 22 '22 23:09

Martijn Courteaux