代码之家  ›  专栏  ›  技术社区  ›  Toolbox

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

  •  0
  • Toolbox  · 技术社区  · 6 年前

    我发现这个问题的标题类似,但没有回答为什么bash脚本中的命令没有被执行:

    Cannot execute shell commands in bash script

    什么管用?

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

    按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
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Akhil    6 年前

    如果要执行所有案例,不应使用break。
    还有在第三种情况下 /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