我正在嘗試撰寫可以使用操作引數啟動的 bash 腳本,并基于該腳本追加、洗掉或覆寫資料檔案,但是當我使用 -a 或 -o 引數時,檔案保持為空或只有白色字符。問題是什么?謝謝!
#!/bin/bash
FILE=/home/xxx/file.data
while getopts 'hadov' CHOICE; do
case "$CHOICE" in
h) echo "-h (help)">&2
echo "-a (append)">&2
echo "-d (delete)">&2
echo "-o (overwrite)">&2
echo "-v (view)">&2;;
a) echo $OPTARG >> $FILE;;
d) if [ -f $FILE ]; then rm $FILE; else echo "file does not exist" > /dev/null;fi;;
v) if [ -f $FILE ]; then cat $FILE; else echo "file does not exist" > /dev/null;fi;;
o) echo $OPTARG > $FILE;;
?) echo bad opt – ${CHOICE} > /dev/stderr
echo bad choice, use -h for help >&2
exit 1;;
esac
done
if [ $OPTIND -eq 1 ];
then
echo "no choice, use -h for help" >/dev/stderr;
exit 1;
fi;
uj5u.com熱心網友回復:
您的getopts命令語法錯誤。?如果您不期望引數值,并且:如果您期望引數值,則必須用 a 分隔可選引數。
所以你的代碼用while-line 替換為
while getopts 'h?a:d?o:v' CHOICE; do
并將在其中./<Script> -o test生成一個檔案test。
有關更多資訊,我建議您閱讀手冊頁
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474238.html
上一篇:Bash-檢查存盤庫是否存在
