为什么我的自定义自动删除 bash 脚本不能正常工作?

为什么我的自定义自动删除 bash 脚本不能正常工作?

我编写了一个如下的 bash 脚本:

#!/bin/bash
echo "this is stand-in for 'sudo apt autoremove --purge'"
echo "Uninstalling ..."
apt autoremove --purge
echo "enjoy your free memory..."

但在转换成可执行文件chmod并运行它之后sudo ./script <package_name>,输出如下:-

this is stand-in for 'sudo apt autoremove-purge'
Uninstalling ...
Reading package lists... Done
Building dependency tree       
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.
enjoy your free memory...

但是如果我使用通常的命令运行相同的代码:- sudo apt autoremove --purge <package_name>,那么它的工作方式如下:-

Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  gstreamer1.0-plugins-base:i386* libaudio2:i386* libcdparanoia0:i386* libdbusmenu-qt2:i386* libgstreamer-plugins-base1.0-0:i386* libgstreamer1.0-0:i386*
  libmng2:i386* libmysqlclient20:i386* libopus0:i386* libqt4-dbus:i386* libqt4-declarative:i386* libqt4-network:i386* libqt4-opengl:i386* libqt4-script:i386*
  libqt4-sql:i386* libqt4-sql-mysql:i386* libqt4-xml:i386* libqt4-xmlpatterns:i386* libqtcore4:i386* libqtdbus4:i386* libqtgui4:i386* libqtwebkit4:i386*
  libtheora0:i386* libvisual-0.4-0:i386* libxss1:i386* libxv1:i386* qt-at-spi:i386* skype* skype-bin:i386* sni-qt:i386*
0 upgraded, 0 newly installed, 30 to remove and 3 not upgraded.
After this operation, 133 MB disk space will be freed.
Do you want to continue? [Y/n] 

我的脚本中缺少什么?

答案1

您目前正在忽略传递给脚本的参数。

它必须看起来像

#!/bin/bash
apt autoremove --purge "$@"

计算"$@"Bash 中传递给脚本的所有参数,因此如果你像这样调用它

sudo uninstall-this-shit sudoku cowsay sl

它将扩大到sudoku cowsay sl

答案2

您需要在内部传递参数

apt autoremove --purge $1

感谢@muru 和@Byte Commander 的注释!

为了使用所有参数,$@应该使用$1

apt autoremove --purge $@

相关内容