跳至内容

Bash - 脚本存根

在我之前工作的地方,我们有一位精通多种语言的编程高手。当你有关于如何用脚本完成某件事的问题时,他也是你的不二之选。他最终创建了一个小存根,一个装满脚本示例的文件,你可以直接提取并根据需要进行编辑。最终,我对这些例程有了足够的了解,以至于我不必再查看存根,但它是一个很好的学习工具,也可能对其他人有用。

实际存根

存根有很好的文档记录,但请记住,这绝不是一个详尽无遗的脚本!还有很多例程可以添加。如果你有适合放入这个存根的示例,请随时添加更改

#!/bin/sh

# By exporting the path, this keeps you from having to enter full paths for commands that exist in those paths:

export PATH="$PATH:/bin:/usr/bin:/usr/local/bin"

# Determine and save absolute path to program directory.
# Attention! In bash, the ' 'represents the string itself; But " " is a little different. $, ` `, and \ represent call variable values, reference commands, and escape characters, respectively
# When done will be in same directory as script:

PGM=`basename $0` # Name of the program
CDIR=`pwd` # Save directory program was run from

PDIR=`dirname $0`
cd $PDIR
PDIR=`pwd`

# If a program accepts filenames as arguments, this will put us back where we started.
# (Needed so references to files using relative paths work.):

cd $CDIR

# Use this if script must be run by certain user:

runby="root"
iam=`/usr/bin/id -un`
if [ $iam != "$runby" ]
then
  echo "$PGM : program must be run by user \"$runby\""
  exit
fi

# Check for missing parameter.
# Display usage message and exit if it is missing:

if [ "$1" = "" ]
then
  echo "$PGM : parameter 1 is required"
  echo "Usage: $PGM param-one"
  exit
fi

# Prompt for data (in this case a yes/no response that defaults to "N"):

/bin/echo -n "Do you wish to continue? [y/N] "
read yn
if [ "$yn" != "y" ] && [ "$yn" != "Y" ]
then
  echo "Cancelling..."
  exit;
fi

# If only one copy of your script can run at a time, use this block of code.
# Check for lock file.  If it doesn't exist create it.
# If it does exist, display error message and exit:

LOCKF="/tmp/${PGM}.lock"
if [ ! -e $LOCKF ]
then
  touch $LOCKF
else
  echo "$PGM: cannot continue -- lock file exists"
  echo
  echo "To continue make sure this program is not already running, then delete the"
  echo "lock file:"
  echo
  echo "    rm -f $LOCKF"
  echo
  echo "Aborting..."
  exit 0
fi

script_list=`ls customer/*`

for script in $script_list
do
  if [ $script != $PGM ]
  then
    echo "./${script}"
  fi
done

# Remove the lock file

rm -f $LOCKF

结论

脚本是系统管理员的朋友。能够快速执行某些任务的脚本可以简化进程完成。虽然这绝不是一套详尽无遗的脚本例程,但这个存根提供了一些常见的用法示例。

作者:Steven Spencer

贡献者:Ezequiel Bruni