我怎样才能使这个脚本更干净?我假设一种方法是创建一些东西来保存各种路径并在这些路径上循环。我还能做些什么来使这个更干净,而不仅仅是重复的循环块吗?
#!/bin/bash/
SRCD='/Users/Connor/Documents/GitHub/WhatThePDF/dat/forms/*.pdf'
for file in $SRCD
do
echo ${file}
destfile="${file/.pdf/_source.txt}"
echo ${destfile}
qpdf --qdf --object-streams=disable ${file} ${destfile}
done
SRCD='/Users/Connor/Documents/GitHub/WhatThePDF/dat/data/*.pdf'
for file in $SRCD
do
echo ${file}
destfile="${file/.pdf/_source.txt}"
echo ${destfile}
qpdf --qdf --object-streams=disable ${file} ${destfile}
done
SRCD='/Users/Connor/Documents/GitHub/WhatThePDF/dat/maps/*.pdf'
for file in $SRCD
do
echo ${file}
destfile="${file/.pdf/_source.txt}"
echo ${destfile}
qpdf --qdf --object-streams=disable ${file} ${destfile}
done
SRCD='/Users/Connor/Documents/GitHub/WhatThePDF/dat/none/*.pdf'
for file in $SRCD
do
echo ${file}
destfile="${file/.pdf/_source.txt}"
echo ${destfile}
qpdf --qdf --object-streams=disable ${file} ${destfile}
done
答案1
我们可以将其简化为单个循环,只需一次传递所有文件名即可:
#!/bin/bash
for file in /Users/Connor/Documents/GitHub/WhatThePDF/dat/{forms,data,maps,none}/*.pdf
do
echo "${file}"
destfile="${file/.pdf/_source.txt}"
echo "${destfile}"
qpdf --qdf --object-streams=disable "${file}" "${destfile}"
done
为了便于阅读,我们可以将其分开一点
例如cd
到目录并在失败时中止:
#!/bin/bash
cd /Users/Connor/Documents/GitHub/WhatThePDF/dat || exit 255
for file in {forms,data,maps,none}/*.pdf
do
echo "${file}"
destfile="${file/.pdf/_source.txt}"
echo "${destfile}"
qpdf --qdf --object-streams=disable "${file}" "${destfile}"
done