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