“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条回答
萌系小妹纸
2楼-- · 2020-02-26 03:36

It depends on where the script is being executed from, if the script is in your $PATH, then it will be based off of the current directory you gave the command from (working directory).

If this is a script being run as a cron job, it's best to use a full directory path.
Example:
cd /home/user/test

Giving the full path will also work if the script is in your $PATH.

查看更多
冷血范
3楼-- · 2020-02-26 03:38

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.

查看更多
Summer. ? 凉城
4楼-- · 2020-02-26 03:40

I faced the same problem in ubuntu. My command shell is:

$ export DIR=mydir

then execute a script file that contains:

#!/bin/sh
cd ~/$DIR

giving output:

cd: 2: can't cd to ~/mydir

by trying many options, at the end it can only be solved like this:

#!/bin/sh
WORKDIR=~/$DIR
cd "$WORKDIR"
查看更多
三岁会撩人
5楼-- · 2020-02-26 03:41

Shouldn't you use

cd /test

instead? I don't know shell scripting, but I can see that your particular script is sensitive to the current directory.

查看更多
神经病院院长
6楼-- · 2020-02-26 03:46

Make sure you are in the right directory

Run the command bellow to known where are you

pwd

Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The cd succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.

Try this

. myscript.sh
查看更多
别忘想泡老子
7楼-- · 2020-02-26 03:47

The answer by Benito Ciaro is on point. I would just like to add another method that you can use to remove \r\n line endings. Open the script in text-editor Sublime and in the menu

Goto View → Line Endings → Unix

This will remove the '\r' character from your script. Don't forget to save your file.

查看更多
登录 后发表回答