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?
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?
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.
Not really relevant for this question. I had the same error message, however, I was using
After changing this to
it was fixed.
I faced the same problem in ubuntu. My command shell is:
then execute a script file that contains:
giving output:
by trying many options, at the end it can only be solved like this:
Shouldn't you use
instead? I don't know shell scripting, but I can see that your particular script is sensitive to the current directory.
Make sure you are in the right directory
Run the command bellow to known where are you
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
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 menuThis will remove the '\r' character from your script. Don't forget to save your file.