Bash脚本,就像makefile一样

时间:2012-03-25 21:26:22

标签: bash

我想制作一个像makefile一样工作的bash脚本。 它有像-archive,-clean,-backup等选项。 唯一的要求是它必须具有-o参数,因此它指定了一个名称。 我现在遇到的问题是我不知道如何从参数中提取.c文件。

例如,如果我输入了 ./compile.sh -o name -backup hello_world.c print.c

我将如何编译?

这是我到目前为止的代码。

#!/usr/local/bin/bash

if [ $1 != '-o' ]; then
echo "ERROR -o wasn't present as first argument"
echo "HELP"
echo "BASH syntax: $ compile –o filename –clean –backup –archive -help cfilenames"
echo "WHERE:"
echo "$             Unix Prompt"
echo "comiple       Name of bash program"
echo "-o filename   Mandatory Argument"
echo "-clean        Optional and when present deletes all .o files"
echo "-backup       Optional and copies all .c and .h files into backup directory"
echo "-archive      Optional and Tars content of source directory. Then moved to backup directory"
echo "-help     Provides list of commands"
echo "cfilenames    Name of files to be compiled together"
fi
NAME=$2
shift
shift

options=$@
arguments=($options)

index=0
for argument in $options
do
    index=`expr $index + 1`
    case $argument in
      -clean) echo "clean" ;;
      -backup) echo "backup"
        mv -f *.c ~/backup
        mv -f *.c ~/backup ;;
      -archive) echo "archive"
        tar -zcvf backup.tar.gz *
        mv -f backup.tar.gz ~/backup/backup.tar.gz
        ;;
      -help) echo "help"
                echo "HELP"
                echo "BASH syntax: $ compile –o filename –clean –backup –archive -help cfilenames"
                echo "WHERE:"
                echo "$             Unix Prompt"
                echo "comiple       Name of bash program"
                echo "-o filename   Mandatory Argument"
                echo "-clean        Optional and when present deletes all .o files"
                echo "-backup       Optional and copies all .c and .h files into backup directory"
                echo "-archive      Optional and Tars content of source directory. Then moved to backup directory"
                echo "-help         Provides list of commands"
                echo "cfilenames    Name of files to be compiled together"
        ;;
esac
done
exit;

由于

1 个答案:

答案 0 :(得分:3)

您似乎在寻找getopts(1P),一个内置用于解析选项的bash。您可以按如下方式使用它:

#!/bin/bash
while getopts "abc:" flag do
    echo "$flag" $OPTIND $OPTARG
done

了解详情:http://aplawrence.com/Unix/getopts.html#ixzz1qAQ29TFW

如果您想使用长选项,可以使用getopt(1),这是一个可以从bash调用的单独程序。它是linux-util的一部分,它是大多数发行版或至少部分基本软件包的默认安装的一部分。