Bash 菜单脚本 - 无法执行命令

工具箱

我正在构建一个最小的标准 bash 菜单。选择工作正常,但没有执行命令。我怀疑我可能会包含在命令中,但不确定这是如何完成的。我经常会发送 2 个命令,因此需要以 bash 将其理解为命令行的方式将命令分开。

我发现this SO question具有类似的标题,但没有回答为什么bash脚本中的命令没有被执行:

无法在 bash 脚本中执行 shell 命令

什么有效,什么无效?

按 1:不更改为正确的 cd。

按 2:在正确的文件夹中创建文件。

按 3:有效。

按 4:Works(R 文件准备为:a <- 1)。

通缉行为:

我需要执行 bash 菜单脚本中的命令。

    #!/bin/bash


# -----
# Menu:
# -----

while :
do
echo "Menu"

echo "1 - Change directory to /tmp"
echo "2 - Create file test1.sh with hello message, in /tmp"
echo "3 - Execute test1.sh"
echo "4 - Execute R-script [/tmp/test2.R]"
echo "Exit - any kind but not [1-4]"

read answer;

case $answer in
    1)
    echo "Change directory to [\tmp]"
    cd /tmp # Command to be executed.
    break
    ;;

    2)
    echo "Create file [test1.sh] in [\tmp]"
    # Commands to be executed.
    cd /tmp
    touch test1.sh
    chmod +x test1.sh
    echo echo "hello" > test1.sh
    break
    ;;
    3)
    echo "Execute file [test1.sh]"
    /tmp/./test1.sh # Command to be executed.
    break
    ;;
    4)
    echo "Execute R-script [/tmp/test2.R]"
     cd /tmp && /usr/bin/Rscript test2.R # Command to be executed.
    break
    ;;

    *)
    # Command goes here
    echo "Exit"
    break
    ;;
esac
done
阿基尔·贾拉甘

当您想执行所有情况时,您不应该使用 break。
并且在您使用的情况 3 中,/tmp/./test1.sh它应该是./tmp/test1.sh或者sh /tmp/test1.sh
您的代码应该是:

#!/bin/bash

# -----
# Menu:
# -----

while :
do
    echo "Menu"

    echo "1 - Change directory to /tmp"
    echo "2 - Create file test1.sh in /tmp"
    echo "3 - Execute test1.sh"
    echo "4 - Execute R-script [/tmp/test2.R]"
    echo "Exit - any kind but not [1-4]"

    read answer;

    case $answer in
        1)
            echo "Change directory to [\tmp]"
            cd /tmp # Command to be executed.
            pwd

        ;;

        2)
            echo "Create file [test1.sh] in [\tmp]"
            touch /tmp/test1.sh # Command to be executed.

        ;;
        3)
            echo "Execute file [test1.sh]"
            ./tmp/test1.sh # Command to be executed.

        ;;
        4)
            echo "Execute R-script [/tmp/test2.R]"
            /usr/bin/Rscript /production/20_front_trader/build/x_run_front_trader.R # Command to be executed.

        ;;

        *)
            # Command goes here
            echo "Exit"

        ;;
    esac
done

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章