1. 程式人生 > >Linux Shell "getopts" 簡記(一) 我的誤解

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 "
[email protected]
" do ls $long $inode $param count=$[ $count + 1 ] done

輸出:

[[email protected] ~]# cd dev/option/
[[email protected] 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

就是這樣↑