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

如何使用目标运行bash脚本?

  •  1
  • Anon  · 技术社区  · 2 年前

    我记得我创建了Makefile,它将允许诸如Clean或Tar之类的目标只在目标添加到末尾时才运行命令。示例:

    航空站

    ./myscript Clean
    

    myscript

    cd testfolder
    python3 main.py
    
    Clean:
        rm -f *.txt
    

    其中rm-f*.txt行只有在用户将Clean添加到命令末尾时才会运行。只是想知道使用bash脚本是否可行,因为它会让我的生活更轻松,而不是使用多个短脚本。如果这不可能,或者我没有足够清楚地提出我的问题,请告诉我!任何帮助都将不胜感激。

    1 回复  |  直到 2 年前
        1
  •  1
  •   TheAnalogyGuy    2 年前

    您可以将参数传递给一个简单的bash脚本,并使用case语句或if语句之类的语句——下面是一个使用case语句的示例,它应该可以工作。

    #!/usr/bin/env bash
    
    # cd to the test folder
    cd testfolder
    
    # run main.py script that does blah blah
    python3 main.py
    
    # parse argument(s)
    case $1 in
      Clean)
        rm -f *.txt
        ;;
      Blah)
        echo "You passed 'Blah' ..."
      ;;
      *)
        echo "Usage: $0 Clean | Blah"
      ;;
    esac 
    

    示例(使用上述内容):

    # simple python script...
    $ cat testfolder/main.py
    print ("hello")
    
    # (add the above contents to to a file named 'myscript')
    # change the mode of the file to make it executable
    $ chmod +x myscript
    
    # generate some test files in the dir
    $ touch testfolder/testfile{1..4}.txt
    
    # show the test files
    $ ls  testfolder/
    main.py  testfile1.txt  testfile2.txt  testfile3.txt  testfile4.txt
    
    # run with no args
    $ ./myscript
    hello
    Usage: ./myscript Clean | Blah
    
    # run with `Blah`
    $ ./myscript Blah
    hello
    You passed 'Blah' ...
    
    # run with 'Clean'
    $ ./myscript Clean
    hello
    
    # show contents now
    $ ls  testfolder/
    main.py
    

    如果你想了解一下正在发生的事情,就和 -x

    例如。

    $ touch testfolder/testfile{1..4}.txt
    
    $ bash -x myscript Clean
    + cd testfolder
    + python3 main.py
    hello
    + case $1 in
    + rm -f testfile1.txt testfile2.txt testfile3.txt testfile4.txt