简体   繁体   English

Mac OS X中的Shell脚本从主目录运行?

[英]Shell Scripts in Mac OS X run from home directory?

I'm a longtime Windows and Linux user and have had some weird experiences writing shell scripts on Mac OS X. In particular, I can write the scripts just fine and run them from the terminal, but every time I try running one from a Finder window it always executes from the user's home directory rather than the directory in which the script lives. 我是Windows和Linux的长期用户,并且在Mac OS X上编写shell脚本有一些奇怪的经历。特别是,我可以编写脚本并从终端运行它们,但每次我尝试从Finder运行一个它始终从用户的主目录而不是脚本所在的目录执行。 That is, if the script is located at 也就是说,如果脚本位于

~/path/to/the/script.sh

it always runs out of ~ . 它总是耗尽~ In the past I've had to ask my more Mac-savvy friends how to fix this, and they've often done so using some perversely awful techniques, but I don't see any reason why this should be the case. 在过去,我不得不问我更多精通Mac的朋友如何解决这个问题,而且他们经常使用一些非常糟糕的技术来做到这一点,但我认为没有任何理由可以解决这个问题。

My question is - is there an easy way to write a shell script in Mac OS X that, when double-clicked in Finder, runs out of the directory in which it resides? 我的问题是 - 有没有一种简单的方法可以在Mac OS X中编写一个shell脚本,当在Finder中双击时,它会用完它所在的目录?

The behaviour seems consistent to me. 这种行为似乎与我一致。 It inherits your finder instances environment, which would be rooted at your home directory. 它继承了您的finder实例环境,该环境将根植于您的主目录。

However, it's not too hard to fix. 但是,修复起来并不难。

cd "$(dirname "$0")"

Ought to do the trick ala: 应该做的伎俩ala:

richh-desktop % fullname.sh 
/home/richh/bin
richh-desktop % cd .. 
richh-desktop % fullname.sh 
/home/richh/bin
richh-desktop %        

If you want the script to run out of the directory it lives in, the script will have to change its working directory. 如果您希望脚本在其所在的目录中运行,则脚本必须更改其工作目录。 Given that your example is written in bash, I'll respond with a bash example. 鉴于您的示例是用bash编写的,我将使用bash示例进行响应。 The $_ value is set to the absolute path of the current script. $ _值设置为当前脚本的绝对路径。 You can find more information by running man bash 您可以通过运行man bash找到更多信息

#!/bin/bash

PROGPATH=$(dirname $_)
cd $PROGPATH

# Do your stuff here

It's going to be up to the script to change the directory for you. 这将取决于脚本为您更改目录。 Check this page out. 查看此页面

$0的目的是解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM