【发布时间】:2014-05-21 16:19:05
【问题描述】:
我编写了一个 shell 脚本,它通过 SSH 连接到远程主机并进行一些处理。远程执行的代码必须使用从属性文件中读取的局部变量。我的代码如下。以下代码未正确执行。它给出了一个错误,
-printf: unknown primary or command.
请帮帮我。
注意:datadir、username 和 ftphostname 在属性文件中定义。
. config.properties
ssh $username@$ftphostname << EOF
filelist=;
filelist=($(find "$datadir" -type f -printf "%T@ %p\n"| sort -n | head -5 | cut -f2- -d" "));
filecount=\${#filelist[@]};
while [ \${#filelist[@]} -gt 0 ]; do
checkCount=;
filesSize=$(wc -c \${filelist[@]}|tail -n 1 | cut -d " " -f1) ;
if [ "\$filesSize" == "\$fileSizeStored" ]; then
fileSizeStored=0;
printf "\n*********** \$(date) ************* " >> /home/chisan/logs/joblogs.log;
echo "Moved below files" >> /home/joblogs.log;
for i in "\${filelist[@]}"
do
# echo "file is \$i"
checkCount=0;
mv \$i /home/outputdirectory/;
if [ $? -eq 0 ]; then
echo "File Moved to the server: \$i" >> /home/joblogs.log;
else
echo "Error: Failed to move file: \$i" >> /home/joblogs.log;
fi
done
filelist=($(find "$datadir" -type f -printf '%T@ %p\n' | sort -n | head -5 | cut -f2- -d" "));
else
((checkCount+=1));
sleep 4;
fileSizeStored=\$filesSize;
fi
done
EOF
但是这个有效
#ssh to remote system and sort the files and fetch the files which are copied first(based on modification time)
ssh -o StrictHostKeyChecking=no user@server 'filelist=($(find /home/data -type f - printf "%T@ %p\n" | sort -n | head -5 | cut -f2- -d" "));
# filelist array variable holds the file names which have the oldest modification date.
#check the directory until it has atleast one file.
while [ ${#filelist[@]} -gt 0 ]; do
filesSize=$(wc -c "${filelist[@]}"|tail -n 1 | cut -d " " -f1) ;
#filesSize contains the total size of the files that are in the filelist array.
if [ -e "$HOME/.storeFilesSize" ]; then
fileSizeStored=$(cat "$HOME/.storeFilesSize");
if [ "$filesSize" == "$fileSizeStored" ]; then
echo "Moved below files" >> /home/joblogs.log;
for i in "${filelist[@]}"
do
mv "$i" /home/dmpdata1 &>/dev/null;
if [ $? -eq 0 ]; then
echo "File Moved to the server: $i" >>/home/joblogs.log;
else
echo "Error: Failed to move file: $i" >>/home/joblogs.log;
fi
done
filelist=($(find /home/data -type f -printf "%T@ %p\n" | sort -n | head -5 | cut -f2- -d" "));
else
sleep 4;
echo "$filesSize" > "$HOME/.storeFilesSize";
fi
else
echo "creating new file";
echo "$filesSize" > "$HOME/.storeFilesSize";
fi
done'
【问题讨论】:
-
在你第一次绕过 while 循环时,
$fileSizeStored不会被定义,因为你只在循环内部的末尾附近定义它。另外,您是否自己进行过任何基本调试,例如开始拉/评论行,看看是哪一个导致了问题? -
你正在逃避完全错误的事情。您的heredoc 必须有
\$remote和$local,其中remote是远程变量。 -
但你也需要保持一致:你有
filelist转义和未转义。 -
-printf: unknown primary or command:这似乎与变量无关,而是与find的一些奇怪的旧版本有关。服务器是什么系统? -
如果您希望远程执行它,您还需要在查找之前转义
$。截至目前,脚本在本地机器上执行find命令