如何将路径(例如,Users/username/)传递给我的swift脚本,以便它始终运行在那里(在给定的路径中),而不管二进制文件下载的位置(即:在下载或桌面等)?
我正在为团队编写一个脚本,并希望确保它在正确的路径上运行,无论它在本地机器上下载到哪里。
运行yourScript
时,在Terminal。app,你或多或少有$> ./yourScript
,对吧?
例如,当你做一个cd
时,你可以做cd ./thePathYouWant
,对吗?./thePathYouWant
是一个参数(也称为启动参数或选项)
在你的Swift脚本中,你可以通过CommandLine.arguments
读取所有的参数。
现在,我猜你的脚本在执行之前需要知道一些文件夹或文件。
所以,用一种简单的方式,像这样启动你的脚本:./yourScript ./Folder/File
可以用CommandLine
读取./Folder/File
。
现在,您可以检查是否在该路径中找到File
。
整个逻辑可以用伪代码表示:
// Parameter Path was provided, and is "correct"
if let parameterPath = parameterPath, checkExistenceOfFile(at: parameterPath) {
//Work normally
// Parameter path was not provided or incorrect, we check if the file exists at this level
} else if checkExistenceOfFile(at: "./File") { //"./File" being the default path, we expect it to be launch at the same level
//Work normally
// We couldn't find the path
} else {
print("File not not found, you can execute the script like this: $>n./yourScript ./Folder/File where "./Folder/File" is the path of the file, or execute $>./yourScript where the file is on the same folder
}