该脚本应该只运行一次。我想在脚本第一次运行时创建一个文件,如果该文件存在,则脚本不会再次运行。
自动启动脚本以使其仅运行一次的最佳、最干净的地方是什么?
答案1
我发现你的问题很有趣所以我尝试弄清楚如何去做。
我的想法是:创建一个运行后可以自行删除的脚本。这样,脚本就可以完成其工作,然后...再见!
以下是代码
#!/bin/bash
# Test script based on informations found on
# http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in
# trying to understand if it's possibile to achieve what asked on
# http://askubuntu.com/questions/161682/how-to-run-a-script-only-a-single-time-ever
# Let's try to find in which directory the script is
# It should account for spaces, link, etc.
SOURCE="${BASH_SOURCE[0]}"
DIR="$( dirname "$SOURCE" )"
while [ -h "$SOURCE" ]
do
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
# We know the name of the script from 'basename $0'
NAME=`basename $0`
# Merge them to have the full path to the script
FULL_PATH=$DIR/$NAME
echo $FULL_PATH
# Let's be a bit theatrical
echo "This script will self destruct in"
for ((i=5;i>0;i--))
do
echo $i
sleep 1
done
# Goodbye!
rm $FULL_PATH
保存此测试代码并使其可执行以进行测试。
请记住,它在运行时会自行删除,因此在测试之前不要忘记备份!