This is an old revision of the document!
(stdin) 0 #Standart input (stdout) 1 #Standart output (stderr) 2 #Standart error output
> #redirects standart input 1> #redirects standart output 2> #redirects standart error output
Examples:
ls /opt/ /otherfile > list 2>&1 #Redirect standart output and standart error output to a file echo "This is a test" 1> /dev/null #Redirects standart output to /dev/null ls xyz > info.txt 2> error.txt #Output of ls will be redirected to "info.txt" (stdout) and if there is an error output (stderr) to "error.txt" ls /opt /otherfolder 2> /dev/null #Output Standartoutput - standarterroroutput will be piped to /dev/null 2> /opt/file #Redirects standart error output 2>> /opt/file #Redirects standart error output (appends)
Explication check:
man -Len -Pless\ +/^REDIRECTION bash
command1 && command2 #Command2 is only executed if command1 completed without errors command1 || command2 #Command2 is only executed if command1 completed with an error
To check if a process is running/ return code:
SERVICE_NAME=apache2
(ps -ef | grep $SERVICE_NAME | grep -v grep && echo "$SERVICE_NAME is running") || echo "$SERVICE_NAME is not running" ps -ef | grep $SERVICE_NAME | grep -v grep && RESULT=running || RESULT=error
Another example:
BACKUPLOG=/var/log/mysql/backup.log ERRLOGFILE=/var/log/mysql/error.log TARGET_FOLDER=/backup/${HOST} HOST="mytesthost"
innobackupex --apply-log $TARGET_FOLDER && /bin/echo "`/bin/date +'%d-%m-%Y %H:%M:%S'`: Backup successful." >> $BACKUPLOG || /bin/echo "`/bin/date +'%d-%m-%Y %H:%M:%S'`: Backup failed." >> $ERRLOGFILE cp -a $(ls /var/log/nginx/*access.log.* | grep -E 'access\.log\.[1-3](\.gz)?$') /mnt/serverlogs/lb-web/
Output one command as input to another command:
cat /etc/passwd | cut -d: -f1 cat /etc/group |cut -d: -f1 command1 | command2 ls -l /etc | less
Output to stdout and a file at the same time:
ls -l | tee outputfilename ls -l | tee -a outputfilename #Append to file outputfilename