如何从 rubygem 命令行工具调用 shell 文件
How to call a shell file from rubygem command line tool
我有一个命令需要 运行 一个 shell 脚本。 shell 文件位于 gem 根文件夹中。当我执行完整路径时,一切正常,但无法获取根路径。
运行 来自 project_creator.rb
的脚本
我用来测试
system("sh /Users/user_name/folder/gem-project/lib/gem/create.sh" + param)
尝试过:
system("sh ../lib/gem/create.sh" + param)
使用__dir__
获取Ruby文件的目录。来自 docs:
Returns the canonicalized absolute path of the directory of the file
from which this method is called. It means symlinks in the path is
resolved. If __FILE__
is nil, it returns nil. The return value equals
to File.dirname(File.realpath(__FILE__))
因此,在您的示例中,您可以执行以下操作:
script = File.join(__dir__, '..', 'create.sh')
exit_code = system("sh #{script")
您还可以使用 system
:
设置 cwd(当前工作目录)
system("create.sh", chdir: __dir__)
或者:
Dir.chdir(__dir__) { system('create.sh') }
我有一个命令需要 运行 一个 shell 脚本。 shell 文件位于 gem 根文件夹中。当我执行完整路径时,一切正常,但无法获取根路径。
运行 来自 project_creator.rb
我用来测试
system("sh /Users/user_name/folder/gem-project/lib/gem/create.sh" + param)
尝试过:
system("sh ../lib/gem/create.sh" + param)
使用__dir__
获取Ruby文件的目录。来自 docs:
Returns the canonicalized absolute path of the directory of the file from which this method is called. It means symlinks in the path is resolved. If
__FILE__
is nil, it returns nil. The return value equals toFile.dirname(File.realpath(__FILE__))
因此,在您的示例中,您可以执行以下操作:
script = File.join(__dir__, '..', 'create.sh')
exit_code = system("sh #{script")
您还可以使用 system
:
system("create.sh", chdir: __dir__)
或者:
Dir.chdir(__dir__) { system('create.sh') }