Linux Shell "getopts" 簡記(一) 我的誤解

在實際工作當中,較多情況下,寫shell程序的時候實際上是爲了簡化重複操作。

一些自己寫的shell自己使用,幾乎都不會有什麼問題,不過偶爾會想,shell往裏面傳參數的時候,如果選項(option)和參數(parameter)個數不固定,這個時候該怎麼辦呢?

正好這周翻到《Linux命令行與shell腳本編程大全》這本書看了一下,就是用shell中的 getopts 這個。

一開始按照自己的理解,照着書上的實例敲了一下。最開始沒有出想要的效果,反覆讀了幾遍,發現首先先要接收劇情設定,舉個例子:

~/$ ./myshell -n "my name" -s "Male" -y /home/user1/log

上面這條命令,-n -s 和 -y都是選項。假如 getopts ":n:s:y" opt

那麼/home/user1/log 就屬於額外的參數。

shift $[ $OPTIND - 1 ]之後,

循環中會有輸出/home/user1/log

如果最後沒有輸/home/user1/log,則最後的一個循環不會有輸出內容

即:書中的shell,最後輸出的,是非選項中的參數,也就是說"my name" 和 "Male" 是不包含在內的!

而我最初以爲,shift後面的循環,可以輸出"my name" 、 "Male" 和 /home/user1/log 三個值。不過後來想想,如果是輸出了三個值,如何判斷哪個是額外參數,就成了一個新的問題。

模擬ls命令的 -l 和 -i 參數:

#!/bin/bash

while getopts ":li" opt
do
        case "$opt" in
        l) long="-l"; echo $long        ;;
        i) inode="-i"; echo $inode      ;;
        *) echo "What's the fuck you input ?!"
        p=$[$OPTIND-1]
        echo "Error: \"${!p}\"";;
        esac
done
shift $[ $OPTIND - 1 ]

count=1
for param in "$@"
do
        ls $long $inode $param
        count=$[ $count + 1 ]
done

 

輸出:

[root@cent-dev ~]# cd dev/option/
[root@cent-dev option]# ./ls -l -i -a . ..
-l
-i
What's the fuck you input ?!
Error: "-a"
total 12
25517749 -rwxr-xr-x. 1 root root 317 Nov  3 14:54 ls
25517746 -rwxr-xr-x. 1 root root 439 Nov  3 13:32 myopt
25517745 -rwxr-xr-x. 1 root root 430 Nov  3 13:30 org
total 40
25574518 drwxr-xr-x. 2 root root 275 Mar 12  2018 autorsa
25575945 -rw-r--r--. 1 root root  32 Sep  5 23:24 config
16797776 -rw-r--r--. 1 root root   9 Feb 10  2018 eof.sh
16815732 -rw-r--r--. 1 root root  26 Feb  9  2018 file
16815730 -rw-r--r--. 1 root root   0 Feb  9  2018 file1
25575946 -rwxr-xr-x. 1 root root 533 Sep 19 22:14 initcg
25600646 -rw-r--r--. 1 root root 226 Oct  3 09:10 input_passwd
17299352 -rwxr-xr-x. 1 root root  80 Feb 21  2018 limit
25517736 -rwxr-xr-x. 1 root root  64 Oct 19 09:04 mon
25180069 drwxr-xr-x. 2 root root 100 Oct 13 10:12 myshell
17299344 -rw-------. 1 root root 791 Feb 22  2018 nohup.out
25574517 prw-r--r--. 1 root root   0 Sep 13 22:57 npipe.txt
25517734 drwxr-xr-x. 2 root root  89 Nov  3 14:54 option
25731125 -rwxr-xr-x. 1 root root 121 Mar 14  2018 remain
17299350 -rwxr-xr-x. 1 root root 666 Feb 22  2018 test

就是這樣↑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章