脚本找不到文件 [英] Script cannot find file
问题描述
我正在尝试在Mac/Linux机器上运行名为 myscript.command
的脚本.
I am trying to run a script named myscript.command
on a Mac/Linux machine.
#!/bin/sh
echo 'Starting'
chmod 777 ./myfile
问题在于,当我进入 chmod
部分时,会得到以下输出:
The problem is that when I get to the chmod
part I get this output:
chmod ./myfile: No such file or directory
但是 myscript.command
和 myfile
都在同一文件夹中.
But both myscript.command
and the myfile
are in the same folder.
编辑
似乎我启动脚本时,脚本的位置未保留.如何保存位置?
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.
推荐答案
$ 0
为了将当前工作目录更改为脚本目录,请在shebang行之后放置以下命令:
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")"
$ 0
变量扩展为脚本名称(脚本的路径),而 dirname
返回脚本目录的路径.
The $0
variable expands to the script name (path to the script), and dirname
returns path to the script's directory.
检测当前工作目录
您可以使用 pwd
命令获取当前的工作目录.如果您实际上正在运行Bash(我不确定,因为代码中的shebang指向/bin/sh
),则可以使用内置的 $ PWD
变量:
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
内置cd
设置的当前工作目录.
PWD
The current working directory as set by thecd
builtin.
将脚本的路径存储到变量中
或者,将目录路径保存到变量中,然后在脚本中使用它,例如:
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"
双引号
请注意使用双引号.双引号可防止重新解释特殊字符.这也是将包含空格的字符串作为单个单词传递的方法:
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.
这篇关于脚本找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!