bash 在bash脚本中执行相对路径可执行文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9914311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute relative path executable in bash script
提问by Huckle
I googled for this senario, but it is flooded with results on how to turn a relative path into an absolute one (which would work, but I feel there is an easier way)
我在谷歌上搜索了这个 senario,但是关于如何将相对路径变成绝对路径的结果充斥着(这会起作用,但我觉得有一种更简单的方法)
I have the following scenario:
我有以下场景:
$ls ../
executable1 dir1
$
$ls
shellscript1
$
$cat ./shellscript1
#!/bin/bash
#Run executable1, which I know is one dir up towards root
../executable1 arg1 arg2 arg3 etc
exit 0
#----End Of Script----
$
$./shellscript1
./shellscript1: line 3: ../executable1: No such file or directory
Essentially I need to call an executable with a relative path from a bash script. It works fine in a bash shell, but in a script it fails to resolve the path. I have verified the working directory is what I expect it to be (i.g., dir1). Is there some callor execlike command I need in front of it? I tried sh ../executable1but of course bash baffs at the executable.
本质上,我需要使用来自 bash 脚本的相对路径调用可执行文件。它在 bash shell 中工作正常,但在脚本中它无法解析路径。我已经验证了工作目录是我所期望的(ig,dir1)。在它前面有我需要的一些call或exec类似的命令吗?我试过,sh ../executable1但当然 bash baffs 可执行文件。
回答by pizza
I just tested this, it is based on your information and seems to work just fine.
我刚刚测试了这个,它基于您的信息,似乎工作得很好。
$ ls ../
dir1 executable1 executable1.c
$
$ cat ../executable1.c
#include <stdio.h>
int main(int argc, char ** argv) {
while (*argv) {printf ("<%s> ",*argv++);}
printf("\n");
return 0;
}
$ cat ./shellscript1
$
#!/bin/bash
#Run executable1, which I know is up dir up towards root
../executable1 arg1 arg2 arg3 etc
exit 0
#----End Of Script----
$
$ ./shellscript1
<../executable1> <arg1> <arg2> <arg3> <etc>
$
$ ls -l ../ ./
./:
total 4
-rwxr-xr-x 1 pizza pizza 133 2012-03-29 00:19 shellscript1
../:
total 16
drwxr-xr-x 2 pizza pizza 4096 2012-03-29 00:24 dir1
-rwxr-xr-x 1 pizza pizza 6501 2012-03-29 00:20 executable1
-rw-r--r-- 1 pizza pizza 126 2012-03-29 00:20 executable1.c
回答by Kashyap
Could be due to permissions on ..or ../executable1
可能是由于权限..或../executable1
user executing ./shellscriptshould have execute permissions on ..AND ../executable1. Does he?
执行的用户./shellscript应该对..AND具有执行权限../executable1。他吗?

