“cd” does not work in shell script

2020-02-26 03:12发布

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?

标签: linux shell cd
11条回答
Bombasti
2楼-- · 2020-02-26 03:50

I had this problem, and was very confused for a while.

It turns out I had set my $CDPATH environment variable, which normally allows regular cd commands to work as usual. However, I was running my script in non-interactive mode, as "sh" (not "bash"), where the behavior is a little different. It seems that a command like:

cd subdir  # works via interactive bash; not in script run via sh.

will work as expected in my interactive login shell, bash, even when CDPATH is set. However, when I run the identical command in a script (using sh), it failed with

myscript.sh: line 9: cd: subdir: No such file or directory

I modified it to be a relative path:

cd ./subdir

and it works! I believe the difference is in how the shell uses CDPATH. In one case, it searches both CDPATH and your current directory, but in the script it only searches CDPATH. This is similar to the behavior of PATH. If you leave . (the current directory) out of your PATH, then you have to type ./localbinary instead of just localbinary to execute that file.

This is my educated guess. When I set / unset CDPATH it breaks / unbreaks the cd subdir command, and cd ./subdir works in all cases for me.

查看更多
forever°为你锁心
3楼-- · 2020-02-26 03:50

2 is the errno for "No such file or directory". Are you sure the script test exists in the working directory of the script?

You might want to cd to a known "good" directory first and then cd into known child directories of that good directory.

查看更多
叼着烟拽天下
4楼-- · 2020-02-26 03:51

Well I got it working using ""

So in your case it would be:

cd "test"

/Marcus

查看更多
在下西门庆
5楼-- · 2020-02-26 03:53

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

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-26 03:57

put pwd as the first line. Then see if that directory has a test subdirectory.

It looks like its running from the root directory

查看更多
登录 后发表回答