Implementation of linux shell using read to input from keyboard in while

高洛峰
Release: 2023-03-05 14:56:01
Original
1232 people have browsed it

系统是ubuntu 14.04 64bit,之前曾想安装Stream来玩dota2,但最终没成功。由于Stream只有32bit,安装Stream时也安装了大量32bit的库。删除Stream后,这些库也一直没管,今天忽然心血来潮,想清理一下系统,把不必要的32bit库都干掉。

dpkg -l | grep "i386"看一下,32bit库太多,一个个敲sudo apt-get purge xxx显然有点累,分析了一下输出,

格式大概如下:

rc libkrb5support0:i386  1.12+dfsg-2ubuntu4  i386 MIT Kerberos runtime libraries - Support library
Copy after login

第2列为包名,第4列是平台,于是决定写一个脚本来删除:

#!/bin/sh
 
#rc libkrb5support0:i386  1.12+dfsg-2ubuntu4  i386 MIT Kerberos runtime libraries - Support library
#
#
pks=`dpkg -l | grep "i386" | awk '{print $2,$4}'`
 
tmp="tmp.file"
 
echo "$pks" > $tmp
 
while read line
do
  name=`echo $line | awk '{print $1}'`
  platform=`echo $line | awk '{print $2}'`
 
  # if [ == ] in bash,buf in dash,if [ = ]
  if [ "$platform" = "i386" ];then
    sudo apt-get purge $name
  fi
done < $tmp
 
rm -rf $tmp
 
exit 0
Copy after login

这个脚本大体上没有什么错,不过在执行sudo apt-get purge $name这一行时,系统询问是否删除。但是这时却没有机会输入,而是直接中止执行。

xzc@xzc-HP-ProBook-4446s:~$ ./rm_i386_package.sh
正在读取软件包列表... 完成
正在分析软件包的依赖关系树   
正在读取状态信息... 完成   
下列软件包将被【卸载】:
 libdrm-radeon1:i386*
升级了 0 个软件包,新安装了 0 个软件包,要卸载 1 个软件包,有 306 个软件包未被升级。
解压缩后会消耗掉 0 B 的额外空间。
您希望继续执行吗? [Y/n] 中止执行。
Copy after login

批量删除软件这操作,当然要一个确认,不能加个参数默认执行啊。

查了一下资料,大概是说

while read line
do
# xxx
done < $file
Copy after login

这样会把read指令重定向为文件$file,这时在while中调用read会直接在文件中取一行作为输入。所以在while中要把read重新定向为终端。上面的脚本稍微修改一行:

sudo apt-get purge $name < /dev/tty
Copy after login

这样就OK了。

以上就是小编为大家带来的linux shell在while中用read从键盘输入的实现全部内容了,希望大家多多支持PHP中文网~

更多linux shell在while中用read从键盘输入的实现相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!