我正在尝试创建一个bash脚本,该脚本将一些pacman查询的输出写入文本文件,这些查询主要是本地安装了哪些程序包,作为依赖项安装的程序包,是孤立程序包以及哪些程序包需要什么依赖性。目前,我正在解决一个问题,该问题使我无法编写需要哪些依赖项的软件包。我正在使用以下bash代码:
#!/bin/bash
set -e -u
#Switch to PWD
cd /home/$USER/System/scripts/pacman-queries-output/
#Get the current date
DATE=`date +%m%d%Y`
#Pacman Queries
pacman --query -e >pacman_installed$DATE.txt
pacman --query -d >pacman_dependencies$DATE.txt
pacman -Qdt >pacman_orphans$DATE.txt
while read package_desc
do
package_name=$(echo $package_desc| cut -d' ' -f 1)
check_if_none=$(pacman -Qi $package_name | grep "Req" | sed -e 's/Required By : //g')
if $check_if_none != "Required By : None"
then
echo $package_name >>pacman_required_by$DATE.txt
pacman -Qi $package_name | grep "Req" | sed -e 's/Required By : //g' >>pacman_required_by$DATE.txt
fi
done < $PWD/pacman_installed$DATE.txt
echo 'Completed 'basename
但是,while循环似乎并没有创建和/或写入我指定的文本文件,相反,它在终端中多次回声:
./ pacman-queries.sh:第20行:必填:找不到命令
以下是运行bash -x pacman-queries.sh时显示的while循环的迭代之一:
+ read package_desc
++ echo aesfix 1.0.1-4
++ cut '-d ' -f 1
+ package_name=aesfix
++ pacman -Qi aesfix
++ grep Req
++ sed -e 's/Required By : //g'
+ check_if_none='Required By : None'
+ Required By : None '!=' 'Required By : None'
pacman-queries.sh: line 20: Required: command not found
有人可以提出解决此问题的任何解决方案吗?先感谢您。
答案 0 :(得分:3)
if $check_if_none != "Required By : None"
如果check_if_none具有字符串:
check_if_none="Required By : None"
然后将其扩展为:
if Required By : None != "Required By : None"
if
尝试执行传递给它的命令。因此它将尝试执行命令Required
。而且找不到这样的命令。
如何修复:
test
[ .. ]
或[[ ... ]]
在bash中进行比较"$varvar"
if [ "$check_if_none" != "Required By : None" ]
也:
修复后的脚本如下所示:
#!/bin/bash
set -e -u
#Switch to PWD
cd "/home/$USER/System/scripts/pacman-queries-output/"
#Get the current date
DATE=$(date +%m%d%Y)
#Pacman Queries
pacman --query -e >"pacman_installed$DATE.txt"
pacman --query -d >"pacman_dependencies$DATE.txt"
pacman -Qdt >"pacman_orphans$DATE.txt"
while IFS= read -r package_desc; do
package_name=$(echo "$package_desc" | cut -d' ' -f 1)
# renamed from check_if_none
# some newlines for readability
Required=$(
pacman -Qi "$package_name" |
grep "Req" |
sed -e 's/Required By : //g'
)
if [ "$Required" != "Required By : None" ]; then
echo "$package_name"
# runnung `pacman -Q` twice is just throwing cpu cycles...
echo "$Required"
fi
# All output goes into required_by - moved it here
# also changed `>>` into `>`
done < "$PWD/pacman_installed$DATE.txt" > "pacman_required_by$DATE.txt"
echo 'Completed 'basename