我正试图通过Laravel调度程序每天从服务器上删除敏感的历史命令
当我运行这段代码时:
$schedule->exec(`for h in $(history | grep mysql | awk '{print $1-N}' | tac) ; do history -d $h ; done; history -d $(history | tail -1 | awk '{print $1}') ; history`)->{$interval}()->emailOutputTo($email)->environments('prod');我知道这个错误:
⚡️ app2020 php artisan schedule:run
ErrorException
Undefined variable: h
at app/Console/Kernel.php:44注意到这是一个完美的工作命令。
for h in $(history | grep mysql | awk '{print $1-N}' | tac) ; do history -d $h ; done; history -d $(history | tail -1 | awk '{print $1}') ; history注意:我知道我可以通过将上面的命令添加到crontab来实现,但目标是将所有cron活动组织在Laravel项目中。
由于bash和PHP使用$作为它们的变量,那么如何使类似的bash命令工作呢?
任何暗示,我都会接受的。
发布于 2020-12-04 21:14:01
您正在用backticks包装您的命令,这既可以插入变量,也可以作为命令执行该值。你不想要这两样东西。
使用单引号构建命令,然后将其传递给exec()。
$cmd = 'for h in $(history | grep mysql | awk \'{print $1-N}\' | tac) ;';
$cmd .= ' do history -d $h ;';
$cmd .= 'done;';
$cmd .= 'history -d $(history | tail -1 | awk \'{print $1}\') ;';
$cmd .= 'history';
$schedule
->exec($cmd)
->{$interval}()
->emailOutputTo($email)
->environments('prod');为了获得更有效的方法,您可以尝试直接编辑历史文件。
$cmd = 'sed -i /mysql/d "$HOME/.bash_history"';没有必要删除文件中的最后一个条目,因为它是交互式shell命令的历史记录。
显然,最好的做法是不要把“敏感”的东西放在命令行中。对于MySQL,可以通过向.my.cnf文件添加凭据来实现这一点。
https://stackoverflow.com/questions/65150445
复制相似问题