Search code examples
bashmakefiletarget

How to run bash script with targets?


I remember creating Makefiles that would allow targets such as Clean or Tar that would only run the commands if the target was added to the end. Example:

Terminal

./myscript Clean

myscript

cd testfolder
python3 main.py

Clean:
    rm -f *.txt

where the rm -f *.txt line would only get run if the user added Clean to the end of the command. Just wondering if this is possible with a bash script because it would make my life easier rather than having multiple short scripts. If it isn't possible or if I didn't propose my question clearly enough just let me know! Any help is appreciated.


Solution

  • You can pass arguments to a simple bash script and use something like a case statement or an if statement - here is an example using a case statement that should work.

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

    Example (using the above contents):

    # 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
    

    If you want to see a little bit under the hood what is happening, run with -x

    e.g.

    $ 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