這個問題有3個部分,每個單是容易的,但組合在一起是不平凡的(至少對我來說):)如何處理shell腳本參數中的「 - 」?
需要編寫一個腳本,應採取什麼作爲它的參數:
- 一個另一個命令名稱
- 幾個參數的命令文件的
- 列表
例子:
./my_script head -100 a.txt b.txt ./xxx/*.txt
./my_script sed -n 's/xxx/aaa/' *.txt
等等。
裏面我由於某種原因,我需要區分
- 什麼命令
- 什麼是該命令的參數腳本
- 哪些文件
所以可能是最標準方式寫上面的例子是:
./my_script head -100 -- a.txt b.txt ./xxx/*.txt
./my_script sed -n 's/xxx/aaa/' -- *.txt
問題1:這裏有更好的解決方案嗎?
處理在./my_script(第一嘗試):
command="$1";shift
args=`echo $* | sed 's/--.*//'`
filenames=`echo $* | sed 's/.*--//'`
#... some additional processing ...
"$command" "$args" $filenames #execute the command with args and files
當filenames
將包含spaces
該解決方案將失效和/或 ' - ',例如
/一些 - 路徑/到/多/白癡的文件name.txt
問題2:如何正確地獲得$command
其爲以後執行$args
和$filenames
?
問題3: - 如何實現以下執行風格?
echo $filenames | $command $args #but want one filename = one line (like ls -1)
這裏是很好的shell解決方案,或者需要使用例如perl嗎?
這將需要一段時間才能回答正確。 1.爲什麼使用back-tics?它們已被棄用,除非您希望以root身份在Solaris或AIX上執行大量工作,而不是必需的。使用$(cmd)! 2.(更多的問題),閱讀getopt和getopts(用於shell)。我在這裏看到了很多例子,至少有一個例子非常詳細。再加上'while(($#> 0))這樣的東西來做processArgs;轉移;完成「將有所幫助。 3.考慮使用案例陳述。對於'--',你可能不得不轉義它們或者引用它們,或者把它轉換成像'[ - ] [ - ]這樣的charclass。 – shellter 2011-05-25 12:20:44