2012-03-25 47 views
0

我想製作一個像makefile一樣工作的bash腳本。 它會有像-archive,-clean,-backup等選項。 唯一的要求是它必須具有-o參數,因此它指定了一個名稱。 我現在的問題是,我不知道如何從參數中提取.c文件。類似makefile的Bash腳本

例如,如果我inputed ./compile.sh -o名稱-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 

[email protected] 
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; 

感謝

+2

爲什麼不直接使用make? – 2012-03-25 21:41:28

+0

我想嘗試新的東西。 – 2012-03-25 21:46:33

回答

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的一部分,它是大多數發行版或至少部分基本軟件包的默認安裝的一部分。

+0

我最初使用getopts,但我讀到你不能使用它長的參數。 – 2012-03-25 21:42:14

+0

相應編輯答案 – 2012-03-25 21:46:36

+0

由於它是一個單獨的程序,是否意味着它不是通用的?例如,我無法將其轉移到另一臺機器上。 – 2012-03-25 21:50:18