2011-01-14 179 views
2

我正在尝试编写一个bash脚本来更改目录,然后在新的工作目录中运行现有的脚本。快速bash脚本在指定文件夹中运行脚本?

这是我到目前为止有:

#!/bin/bash 
cd /path/to/a/folder 
./scriptname 

脚本名称是存在于/路径中的可执行文件/到/一个/文件夹 - 和(不用说了),我确实有运行权限脚本。

然而,当我运行这个头脑麻木简单的脚本(上图),我得到的回应:

脚本名:没有这样的文件或目录

我在想什么?这些命令在CLI中输入时按预期工作,因此我无法解释错误消息。我该如何解决?

+0

嗯,通过许多(不同的)反应来判断 - 包括一两个肯定会过度的反应 - 我不禁会奇怪 - 当然,必须有一种简单的方法来转换文件夹并运行脚本夹? – skyeagle 2011-01-14 15:21:30

+0

您尚未将脚本复制到该文件夹​​。 ./scriptname表示脚本位于该文件夹中,而不是这种情况。通过给出正确的路径来调用脚本。 – BZ1 2011-01-17 04:23:35

+0

您可以添加以下内容作为您想要的别名吗? “bash /path/to/script/script.sh” – Hemm 2013-04-21 01:10:20

回答

3
cd /path/to/a/folder 
pwd 
ls 
./scriptname 

which'll告诉你什么是它认为它在做什么。

4

看着你的脚本让我觉得你想要启动脚本的脚本位于最初的目录。由于您在执行之前更改了目录,因此无法使用。

我建议以下修改后的脚本:

#!/bin/bash 
SCRIPT_DIR=$PWD 
cd /path/to/a/folder 
$SCRIPT_DIR/scriptname 
+0

不,你一定误解了我。我想在/ path/to/a /文件夹中运行脚本(这就是为什么我首先要“cd/path/to/a/folder”)。 – skyeagle 2011-01-14 15:15:20

1

我通常在我的有用脚本目录是这样的:

#!/bin/bash 

# Provide usage information if not arguments were supplied 
if [[ "$#" -le 0 ]]; then 
     echo "Usage: $0 <executable> [<argument>...]" >&2 

     exit 1 
fi 

# Get the executable by removing the last slash and anything before it 
X="${1##*/}" 

# Get the directory by removing the executable name 
D="${1%$X}" 

# Check if the directory exists 
if [[ -d "$D" ]]; then 
     # If it does, cd into it 
     cd "$D" 
else 
     if [[ "$D" ]]; then 
       # Complain if a directory was specified, but does not exist 
       echo "Directory '$D' does not exist" >&2 

       exit 1 
     fi 
fi 

# Check if the executable is, well, executable 
if [[ -x "$X" ]]; then 
     # Run the executable in its directory with the supplied arguments 
     exec ./"$X" "${@:2}" 
else 
     # Complain if the executable is not a valid 
     echo "Executable '$X' does not exist in '$D'" >&2 

     exit 1 
fi 

用法:在这些条件下,这样的错误消息

$ cdexec 
Usage: /home/archon/bin/cdexec <executable> [<argument>...] 
$ cdexec /bin/ls ls 
ls 
$ cdexec /bin/xxx/ls ls 
Directory '/bin/xxx/' does not exist 
$ cdexec /ls ls 
Executable 'ls' does not exist in '/' 
0

一个来源是一个破碎的符号链接。

但是,你说脚本在从命令行运行时工作。我也会检查目录是否是一个符合你所期望的以外的符号链接。

如果您在脚本中使用完整路径而不是使用cd调用它,它会工作吗?

#!/bin/bash 
/path/to/a/folder/scriptname 

从命令行调用这种方式怎么样?