繁体   English   中英

用于在指定文件夹中运行脚本的快速bash脚本?

[英]Quick bash script to run a script in a specified folder?

我正在尝试编写一个更改目录的bash脚本,然后在新的工作目录中运行现有脚本。

这是我到目前为止:

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

scriptname是存在于/ path / to / a / folder中的可执行文件 - 并且(不用说),我有权运行该脚本。

但是,当我运行这个令人讨厌的简单脚本(上面)时,我得到了响应:

scriptname:没有这样的文件或目录

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

查看脚本会让我想到要启动脚本的脚本,该脚本位于初始目录中。 由于在执行之前更改了目录,因此无效。

我建议修改以下脚本:

#!/bin/bash
SCRIPT_DIR=$PWD
cd /path/to/a/folder
$SCRIPT_DIR/scriptname
cd /path/to/a/folder
pwd
ls
./scriptname

它会告诉你它认为它正在做什么。

我通常在我有用的脚本目录中有这样的东西:

#!/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 '/'

在这些条件下,此类错误消息的一个来源是损坏的符号链接。

但是,您说从命令行运行时脚本可以正常工作。 我还要检查该目录是否是一个符合您期望的符号链接的符号链接。

如果您使用完整路径在脚本中调用它而不是使用cd,它是否有效?

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

从命令行调用那个方法怎么样?

暂无
暂无

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

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