5. The terms of the sequence $\left\{a_{n}\right\}$ are all positive, and the sum of the first $n$ terms $S_{n}$ satisfies
$$
S_{n}=\frac{1}{2}\left(a_{n}+\frac{1}{a_{n}}\right) .
$$

Then $a_{n}=$
5. $\sqrt{n}-\sqrt{n-1}$.

From $a_{1}=S_{1}=\frac{1}{2}\left(a_{1}+\frac{1}{a_{1}}\right)$, we get $a_{1}=S_{1}=1$.
When $n>1$, we have
$$
\begin{array}{l}
S_{n}=\frac{1}{2}\left(a_{n}+\frac{1}{a_{n}}\right) \\
\Rightarrow S_{n-1}+a_{n}=\frac{1}{2}\left(a_{n}+\frac{1}{a_{n}}\right) \\
\Rightarrow S_{n-1}=\frac{1}{2}\left(-a_{n}+\frac{1}{a_{n}}\right) .
\end{array}
$$
(1) + (2) gives $S_{n}+S_{n-1}=\frac{1}{a_{n}}$.

Also, $S_{n}-S_{n-1}=a_{n}$,
(3) $\times$ (4) gives $S_{n}^{2}-S_{n-1}^{2}=1$.

Thus, $\left\{S_{n}^{2}\right\}$ forms an arithmetic sequence, $S_{n}^{2}=n, S_{n}=\sqrt{n}$.
Therefore, $a_{n}=S_{n}-S_{n-1}=\sqrt{n}-\sqrt{n-1}$. When $n=1$, this formula also holds.
In conclusion, $a_{n}=\sqrt{n}-\sqrt{n-1}$.