如何运行bash脚本与目标?



我记得创建了makefile,它允许Clean或Tar等目标只在目标添加到末尾时才运行命令。例子:

终端

./myscript Clean

myscript

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

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

您可以将参数传递给一个简单的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

最新更新