php - 运行另一个需要双引号的命令的 Linux 脚本
问题描述
我正在做一场噩梦,试图让它正确运行。我使用 php 代码做得很好,但问题是命令超时的文件很多。我以为我可以通过盒子本身上的 ssh 轻松做到这一点,但我无法让它做我想做的事。
在 PHP 中,我正在执行以下操作:
$command='/usr/bin/convert "'. $LocalPDFURL . '[1]" -quality 70% "' . $LocalJPGURL . '"' ;
我需要搜索 pdf 文件,如果没有使用 pdf 的第一页生成 jpg,则检查它们是否具有具有相同文件名的 .jpg。以上在 php.ini 中运行良好。但是在 linux shell 脚本中,无论我尝试了什么,它都不会起作用。我尝试了各种组合,它要么将整个内容输出为字符串,要么输出错误,因为它没有传递指定完整文件路径所需的双引号(它们包含空格)。
我的脚本是这样的:
format=*.pdf
wpath=$format
for i in $wpath;
do
if [[ "$i" == "$format" ]]
then
echo "No PDF Files to process!"
else
echo "full file name: $i"
FILE="${i%.pdf}.jpg"
if [ -f "$FILE" ]; then
echo "$FILE exists."
else
ORIGINAL=\""${FILE%.jpg}.pdf\""
QFILE=\""$FILE%\""
echo "$FILE does not exist. Creating PDF Cover JPG!"
command="/usr/bin/convert "\""$ORIGINAL"\" 1 -quality 65% $QFILE 2>&1"
echo $command
fi
fi
done
我只想构建命令并执行它。
php 命令输出如下所示...
"/usr/bin/convert "/home/test/1.pdf" 1 -quality 65% "/home/test/1.jpg" 2>&1"
并且运行良好。
我试过单引号,双引号转义它们等。请有人帮忙!
解决方案
所以我的建议如下:
- 在 bash 中创建一个函数来执行您想要的操作(即:给定一个 pdf 文件,检查相应的 jpg 文件是否存在,如果不进行转换)
- 将该功能应用于所有 pdf 文件
maybe_convert(){
! [ -f "${1%.*}.jpg" ] && echo "/usr/bin/convert \"$1\" 1 -quality 65% \"${1%.*}.jpg\"" || echo $1 exists
}
export -f maybe_convert
find . -type f -name "*.pdf" | xargs -I{} bash -c "maybe_convert \"{}\""
上面的代码片段适用于以下文件结构(假设您已将代码片段保存在名为 的文件中convert_image.sh
):
$ ls testdir/
'file 1.jpg' 'file 1.pdf' 'file 2.pdf' 'file 3.pdf'
$ bash convert_image.sh
/usr/bin/convert "./testdir/file 3.pdf" 1 -quality 65% "./testdir/file 3.jpg"
/usr/bin/convert "./testdir/file 2.pdf" 1 -quality 65% "./testdir/file 2.jpg"
./testdir/file 1.pdf exists
推荐阅读
- javascript - 从 HTML 元素 ( ) 执行 JavaScript 函数,不带条件但带参数
- rust - “部分移动后在此处使用的值”错误
- python - 如何解决 NameError:AWS Lambda 中未定义选项?
- google-chrome-extension - Chrome.webRequest.onBeforeRequest - 在 POST 上传文件,但 requestBody.raw 为空
- postgresql - Postgres 13.3 中重载函数的奇怪行为
- google-cloud-platform - 是否可以连接到 GCP Vertex AI 管道中 Cloud SQL 实例的私有 IP?
- php - “the_title”也改变了菜单项
- sql - 如何为雪花中的每一行一次更新每一列
- c++ - 为什么,我得到一些奇怪的垃圾值?
- ssl - 将 .cer 转换为 .pem,将 .key 转换为 .pem