2025-02-18 14:37:26 +01:00

108 lines
2.7 KiB
TeX

\section{Datei einlesen}
%\subsection{Up / Down}
\begin{flushleft}
Eine Datei kann man mit {\ttfamily IFS} und {\ttfamily read} einlesen. Die Datei wird direkt in Variablen gespeichert.
\listBash
\begin{lstlisting}[captionpos=b, caption=Read Datei]
uws@tux>cat DemoRead.sh
#!/usr/bin/env bash
#
# Einlesen der Datei mit dem Feldtrenner :
while IFS=: read BENUTZERNAME A B C D HOMEDIR E; do
printf "$BENUTZERNAME -> $HOMEDIR\n"
done < /etc/passwd
# Als Tabelle
printf "|%23s | %-30s |\n" "Username" "Homedir"
printf "+%23s + %-30s +\n" "-----------------------" "------------------------------"
while IFS=: read BENUTZERNAME A B C D HOMEDIR E; do
printf "|%23s | %-30s |\n" $BENUTZERNAME $HOMEDIR
done < /etc/passwd
printf "+%23s + %-30s +\n" "-----------------------" "------------------------------"
# Einlesen der Datei mit dem Feldtrenner Leerzeichen
while IFS=" " read A1 A2; do
printf "$A1 : $A2\n"
done < liste.txt
# Return code Auswertung
declare -a RESULT
for SRV in $(cat server.lst)
do
ssh -x ${USER}@${SRV} 'ls' 2> /dev/null
status=$?
if [[ $status -gt 0 ]]
then
RESULT+=("$SRV")
printf "Server: ${SRV}\n"
else
printf " Ok: ${SRV}\n"
fi
done
for i in ${!RESULT[*]}
do
printf "Not Ok: ${RESULT[$i]}\n"
done
uws@tux>cat liste.txt
Erste Zeile
Zweite Zeile
Letzte Zeile
\end{lstlisting}
\newpage
\listBash
\begin{lstlisting}[captionpos=b, caption=DemoReadFile.sh]
uws@tux>cat daten.xt
Das ist Zeile 1.
Das ist Zeile 2.
Das ist Zeile 3.
Das ist Zeile 4.
uws@tux>cat DemoReadFile.sh
#!/bin/env bash
while read line
do
echo -e "$line \n"
done < daten.txt
\end{lstlisting}
Eine Datei einlesen, in der die Daten durch einen Separator getrennt sind.
\listBash
\begin{lstlisting}[captionpos=b, caption=DemoReadFileSeparator.sh]
uws@tux>cat DemoReadFileSeparator.sh
#!/bin/env bash
while IFS=':' read user pass uid gid full home shell
do
echo -e "$full:\n\
PSEUDO: $user\n\
UID : $uid\n\
GID : $gid\n\
HOME : $home\n\
Shell : $shell\n\n"
done < /etc/passwd
\end{lstlisting}
Die Kommentar Zeilen einer Datei nicht auswerten. In dem nachfolgenden Beispiel werden sie extra ausgegeben.
\listBash
\begin{lstlisting}[captionpos=b, caption=DemoReadFileComments.sh]
uws@tux>cat DemoReadFileComments.sh
!#/bin/env bash
i=1
while IFS=';' SOURCE BACKUP
do
if [ "${SOURCE:0:1}" != "#" ]; then
printf "\tQuell Path: $SOURCE\n"
printf "\tBackup Path: $BACKUP\n\n"
else
printf "\tComment $((i++)); $SOURCE\n\n"
fi
done <$1
\end{lstlisting}
Eine Variable kann folgenderma\ss{}en eine Datei einlesen.
\listBash
\begin{lstlisting}[captionpos=b, caption=VariableRead]
uws@tux>export VALUE=`cat pd.dat`
uws@tux>export VALUE=$(<pid.dat)
\end{lstlisting}
\end{flushleft}