> ## Content Index
> Fetch the complete content index at: https://blog.skitisu.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# command文件 - 在macOS下编写双击运行的脚本及获取当前目录执行相关命令（类似Windows下的bat）
- URL: https://blog.skitisu.com/mac-os-command-file/
- Published: 2017-02-10T01:31:54.000Z
- Updated: 2019-06-01T18:48:58.000Z
- Author: SkiTiSu
- Tags: 探索, 软件, #Import 2026-10-21 14:41

例如，需要使用mono运行当前目录下的xiaoruanjian.exe，使用编辑器编写：

```bash
#!/bin/bash

cd $(dirname $BASH_SOURCE) || {
    echo Error getting script directory >&2
    exit 1
}

mono xiaoruanjian.exe
```

然后保存为*filename.command*，即可双击运行。第一行的作用是声明使用bash进行解析，这是所有类Unix Shell都应该加上的声明。 第二段的作用是获取当前路径并转到该路径，如果获取时出现错误，就打印错误并退出。当然，你也可以选择保存在变量中：

```bash
mydir=$(cd $(dirname $BASH_SOURCE) && pwd) || {
    echo Error getting script directory >&2
    exit 1
}
```

接下来只要使用*$mydir*即可进行引用，如打印当前目录下的文件和目录： \`\`\`

```bash
ls $mydir
```

> **参考**  
> [http://superuser.com/questions/503253/how-to-specify-batch-command-file-current-location-in-mac-os-x/503278](http://superuser.com/questions/503253/how-to-specify-batch-command-file-current-location-in-mac-os-x/503278?ref=blog.skitisu.com)  
> [http://stackoverflow.com/questions/5125907/how-to-run-a-shell-script-in-os-x-by-double-clicking](http://stackoverflow.com/questions/5125907/how-to-run-a-shell-script-in-os-x-by-double-clicking?ref=blog.skitisu.com)