3

I am trying to run a script named myscript.command on a Mac/Linux machine.

#!/bin/sh echo 'Starting' chmod 777 ./myfile 

The problem is that when I get to the chmod part I get this output:

chmod ./myfile: No such file or directory 

But both myscript.command and the myfile are in the same folder.

EDIT

It seems that when I launch the script the script's location is not being preserved. How can I preserve the location?

The script is being launched via double click in the UI.

13
  • Is the file there? Commented Dec 2, 2016 at 2:34
  • Yes, the file is there. Commented Dec 2, 2016 at 2:36
  • I think it'd be helpful if you also shared the output of "ls -l" from that directory. Note that the script will be indifferent to which directory you start it from... but will check the "current" directory for the file. Commented Dec 2, 2016 at 2:45
  • It looks like ./ is not giving me the folder I am currently in but the root directory of my computer. Commented Dec 2, 2016 at 2:52
  • How exactly are you running myscript.command, from the current directory as ./myscript.command, or something like bash /path/to/myscript.command? Commented Dec 2, 2016 at 2:54

2 Answers 2

7

$0

In order to change the current working directory to the script's directory, put the following command right after the shebang line:

cd "$(dirname "$0")" 

The $0 variable expands to the script name (path to the script), and dirname returns path to the script's directory.

Detecting the current working directory

You can use pwd command to get the current working directory. If you are actually running Bash (I'm not sure, since the shebang in your code points to /bin/sh), you can use the built-in $PWD variable:

PWD The current working directory as set by the cd builtin.

Storing the script's path into variable

Alternatively, save the directory path into a variable, and use it in the script, e.g.:

dir="$(cd $(dirname "$0"); pwd)" chmod 770 "$dir/somefile" 

Double quotes

Note the use of double quotes. Double quotes prevent reinterpretation of special characters. It is also the way to pass strings containing spaces as a single word:

dir="some directory name" cd "$dir" 

Without double quotes the words are interpreted as separate arguments.

Sign up to request clarification or add additional context in comments.

Comments

-1

You might start off something like this, too..

#!/bin/sh echo 'Starting' if [ -f ./myfile ]; then chmod 777 ./myfile else echo "File does not exist:" ls -l fi 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.