Issue
I want to count the number of files of a given type on a remote server. For that I need to ssh and run the commands to count the files on the remote server and then somehow return that value. I thought about just printing the value and trying to capture that output
What I have so far is:
START=0
LAST=5
ssh -i $KEY $USERNAME@$HOST << EOF
N_FILES=0;
for (( d=$START; d<=$LAST; d++ ))
do
check_day=`date +"%Y-%m-%d" -d "$d day ago"`
FILES_FOUND="\$(find &DIR | grep $check_day | wc -l)"
N_FILES=\$(( \$N_FILES + \$FILES_FOUND ))
done
echo $N_FILES
EOF
N_FILES=$?
The above code runs fine but yields 0, when there are actually files found in the server co capturing the output this way is not working. Can somebody help here please?
Solution
You could simply assign the result of the SSH command to a variable:
IFS="" N_FILES=$(ssh -Ti $KEY $USERNAME@$HOST << EOF
N_FILES=0;
for (( d=$START; d<=$LAST; d++ ))
do
check_day=`date +"%Y-%m-%d" -d "$d day ago"`
FILES_FOUND="\$(find &DIR | grep $check_day | wc -l)"
N_FILES=\$(( \$N_FILES + \$FILES_FOUND ))
done
echo $N_FILES
EOF
)
echo $N_FILES
Note: the N_FILES
before ssh is not the same N_FILES
used inside the ssh command.
But its value (provided none of the other ssh commands have any output) will be the same.
The -T
seems important here: no need to request a pseudo-TTY to assign the output to a variable.
Answered By - VonC Answer Checked By - Senaida (WPSolving Volunteer)