[英]awk command not executed within bash script but works fine on the commandline
[英]Awk syntax error when command is executed through a shell script however the command works fine when executed from Linux bash shell
我正在運行此命令
awk '{print "Removing " ORS $0;system("rm " $0 ORS " if [ $? -eq 0 ]" ORS "then" ORS "echo file " $0 " has been removed." ORS "fi")}' <(cat /tmp/findo)
在bash上,該命令有效,但是從shell腳本執行時會引發基本錯誤
這是示例,您可能會看到“第23行錯誤”
# sh -x rvarlog_util.sh
+ findout=/tmp/findout
+ '[' -e /tmp/findout ']'
++ du -sm /var/log
++ awk '{print $1+0}'
+ cdu=2372
++ awk '{print $1+0}'
++ grep total
++ du -m --max-depth=1 -c -m -x /var/log/messages /var/log/messages-20190310 /var/log/messages-20190323-1553338190.gz /var/log/messages-20190324-1553424406.gz /var/log/messages-20190324-1553456095.gz /var/log/messages-20190324-1553456293.gz /var/log/messages-20190324-1553457237.gz /var/log/messages-20190324-1553457268.gz /var/log/maillog-20190324-1553456095.gz /var/log/boot.log /var/log/audit/audit.log /var/log/audit/audit.log-20190311-1552325090.gz /var/log/puppetlabs
+ fusage=2258
rvarlog_util.sh: line 23: syntax error near unexpected token `('
rvarlog_util.sh: line 23: `awk '{print "Removing " ORS $0;system("rm " $0 ORS " if [ $? -eq 0 ]" ORS "then" ORS "echo file " $0 " has been removed." ORS "fi")}' <(cat /tmp/findo)'
@Ibraheem有正確的解決方案,但到目前為止,沒有人發現問題。 這是因為您使用的是進程替換( <(cat /tmp/findo)
),但是使用sh
而不是bash
運行腳本。 並非在所有shell中都可用進程替換(甚至在以“ sh”調用時甚至不是bash)都可用。
有兩種方法可以解決此問題,建議您同時進行兩種操作(因為它們本身就是好主意):
不要使用<(cat somefile)
,請使用普通的重定向,例如<somefile
。 進程替換的cat
命令是一種從文件讀取的過於復雜,脆弱和低效的方式。
給腳本適當的shebang行( #!/bin/bash
或#!/usr/bin/env bash
),使其可執行( chmod +x rvarlog_util.sh
),然后通過輸入其路徑( ./rvarlog_util.sh
直接運行它./rvarlog_util.sh
),而不是顯式指定shell( sh
或bash
)。 通常,腳本應該“知道”要為其編寫的shell,並重寫它(通過在運行時顯式指定shell)是個壞主意。
從awk命令中,我了解到您正在嘗試刪除/ tmp / findo文件中名稱相同的文件,對嗎? 然后將您的awk命令替換為以下代碼,並查看其是否有效,但請確保/tmp/findo
中的文件名包含您要刪除的所需文件的絕對路徑
while read -r files
do
rm "$files"
if [ $? -eq 0 ]
then
"echo $files has been removed."
fi
done < /tmp/findo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.