首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Getopts函数问题

Getopts函数问题
EN

Stack Overflow用户
提问于 2021-07-07 22:14:28
回答 1查看 35关注 0票数 0

尝试创建一个bash脚本,将文件移动到回收站目录中,并具有其他一些功能。为了实现这些功能,我正在尝试使用getopts函数,但我正在努力实现帮助功能或用户手册。当我运行脚本并尝试使用-h时,脚本没有识别出它是一个选项,只是正常运行,就像它是一个文件一样。我该如何解决这个问题呢?已修复:

代码语言:javascript
复制
#!/bin/bash
trash=~/TRASH
if [ ! -e $trash ]; then
  mkdir $trash
elif [ ! -d $trash ]; then
  echo "$0: error: $trash is not a directory"; exit 1
fi

while getopts "h" options; do
case $options in
h) echo "This is the help option."
exit;;
\?)
echo: "Invalid option"
exit;;
esac
done

while [ $# -gt 0 ]; do
  if [ ! -e $1 ]; then
    echo "$0: error: tried to delete file that does not exist: $1"
    shift
    continue
  fi
  tarname="$1.tar"
  tar -cf "$tarname" "$1"
  mv "$tarname" $trash
  rm -rf "$1"
  shift
done


echo "Cleaning $trash directory"
now=`date +%s`
cd $trash
for f in `ls`; do
  fileage=$(stat -c '%Y' "$f")
  if [ $((now-fileage)) -gt $((60*60*24*2)) ]; then
    rm -rf "$f"
  fi
done
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-07 22:27:29

这是一个简单的修复,只需将getopts函数移动到顶部,在任何其他操作之前发生,现在它就可以工作了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68287733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档