Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

linux - Script cannot find file

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...