bash script notes (1)

I tied to study the shell script a few times. But on that time, I didn’t get enough knowledge to deal with it. Now, I’m back.

Situation 1

I want to startup the vpn service when the computer startup. I added pon vpn_name to rc.local. However, this can be failed because when this line execute, the network may not be ready. So I decide to write a script to do this. It will wait until the Internet up. Here’s it.

#!/bin/bash

sleep_time=1
export PATH=$PATH:/usr/bin

while [ 1 ]
do
  ping_success=`ping -c 1 -n vpn.yegong.net | \
    sed -n -r 's/^.* (.) received.*$/\1/p'`
  if [ $ping_success -eq 1 ]
  then
    pon yegong
    exit 0
  fi
  sleep $sleep_time
  sleep_time=$(expr $sleep_time + 1)
done
  1. export PATH is very important.
  2. `ping -c 1 -n vpn.yegong.net | sed -n -r ’s/^.* (.) received.*$/\1/p’`, using ` surround the command to get the output text.
  3. sed -n -r ’s/^.* (.) received.*$/\1/p’, using sed to simplify the output. It’s the regular expression. Very similar with VIM replace syntax, isn’t it?
  4. if [ $ping_success -eq 1 ], [ condition ] means the test program, equivalent to test condition, so man test will show more usage.
  5. sleep_time=$(expr $sleep_time + 1), it seems that every variable in shell is a string, so you can’t simply write x=x+1. Instead of, expr program read a string expression and output the results. Please notice the space in the expression.

Situation 2

For each text files in a directory, convert the file encoding to utf8.

There’s a simple util can guess the file encoding. It can be found at Wu Yongwei’s Programming Page (Can’t access when I write the article). Then I just need a script to combine the tellenc and iconv.

TMP_FILE="/tmp/utf8lize.output"
ENCODING="utf-8"

if [ $# == 0 ]
then
  echo "Usage: utf8lize FILES"
  exit 1
fi

for f in "$@"
do
  if [ -f "$f" ]
  then
    enc=`tellenc "$f"`
    if [ $enc != $ENCODING ] && [ $enc != "binary" ]
    then
      echo $f : $enc
      cp "$f" "$f.bak"
      iconv -f "$enc" -t "$ENCODING" -o "$TMP_FILE" "$f"
      cp "$TMP_FILE" "$f"
      rm -f "$TMP_FILE"
    fi
  fi
done
  1. $# results the number of arguments when it been executed.
  2. for f in “$@” is the for-each loop. And “$@” indicates the all program arguments. In addition, when you run the program utf8lize *, * will convert to filenames array. Using the ” to surrounding $@ can deal the filename with space.

你可能会感兴趣

on December 15th, 2009 | No Comments »

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>