Programming‎ > ‎

Shel Script



File check


if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

Check HAProxy config failure

# Check the config file for errors
    /usr/local/sbin/haproxy -c -q -f /etc/haproxy/haproxy.conf
    if [ $? -ne 0 ]; then
            echo "Errors found in configuration file."
            return 1
      fi

 -c only checks config file and exits with code 0 if no error was found, or
       exits with code 1 if a syntax error was found.

Check Process instance

#!/bin/bash
 
# check if we are the only local instance
if [[ "`pidof -x $(basename $0) -o %PPID`" ]]; then
	echo "This script is already running with PID `pidof -x $(basename $0) -o %PPID`"
	exit
fi
 
# start your script here

Check Process Common Name

ps -p 1337 -o comm=
Here, the process is selected by its PID with -p. The -o option specifies the output format, commmeaning the command name.

String Manipulation


http://www.thegeekstuff.com/2010/07/bash-string-manipulation/ 
Replace all the matches 
${string//pattern/replacement}


How to set a variable to the output from a command in Bash

In addition to the backticks, you can use $(), which I find easier to read, and allows for nesting.

OUTPUT="$(ls -1)"
echo "${OUTPUT}"

Quoting (") does matter to preserve multi-line values.


Comments