Difference between revisions of "Bash notes"

From Noah.org
Jump to navigationJump to search
Line 64: Line 64:
 
     echo "You are root."
 
     echo "You are root."
 
     exit 0
 
     exit 0
 +
fi
 +
</pre>
 +
 +
<pre>
 +
if [ $(id -u) != 0 ]; then
 +
    echo "You must be root to run this."
 +
    exit 1
 
fi
 
fi
 
</pre>
 
</pre>

Revision as of 00:19, 5 December 2008


Turn off bash history for a session

set +o history

Rename a group of files by extension

For example, rename all images from foo.jpg to foo_2.jpg.

This is somewhat more clear:

for filename in *.jpg ; do mv $filename `basename $filename .jpg`_2.jpg; done

This is more "correct" and doesn't require `basename`:

for filename in *.jpg ; do mv $filename ${filename%.jpg}_2.jpg; done

Variable Expansion and Substitution

Bash can do some freaky things with variables. It can do lots of other substitutions. See "Parameter Expansion" in the Bash man page.

  • ${foo#pattern} - deletes the shortest possible match from the left
  • ${foo##pattern} - deletes the longest possible match from the left
  • ${foo%pattern} - deletes the shortest possible match from the right
  • ${foo%%pattern} - deletes the longest possible match from the right
  • ${foo=text} - If $foo exists and is not null then return $foo. If $foo doesn't exist then create it and set value to text.

Statements

Loop on filenames in a directory

for foo in *; do {
  echo ${foo}
}; done

Loop on lines in a file

for foo in $(cat data_file.txt); do {
  echo ${foo}
}; done

while loop

This is kind of like `watch`:

while sleep 1; do lsof|grep -i Maildir; done

check if running as root

if [ `id -u` = "0" ]; then
    echo "You are root."
    exit 0
fi
if [ $(id -u) != 0 ]; then 
    echo "You must be root to run this."
    exit 1
fi

check if process is running

Show the pids of all processes with name "openvpn":

ps -C openvpn -o pid=

Show if a process with pid=12345 is running:

kill -0 12345
echo $?

Check if a process with a given command name and pid is still running. For example, check if ssh process is running with pid 12345: "checkpid ssh 12345". Checkpid script:

#!/bin/sh
# example: checkpid ssh 12345
CMD=$1
PID=$2
for QPID in $(ps -C $CMD -o pid=); do {
    if [ $QPID = $PID ]; then
        echo "running"
        exit 0
    fi
}; done
echo "not running"
exit 1