我有bash文件example.sh:
#!/bin/bash
VAR=''
# if VAR empty - run this
if [-z "${VAR}" ]; then
# some complex formula for VAR. Output is string.
VAR = 'blablabla'
fi
我需要在下一次运行中:
#!/bin/bash
VAR='blablabla'
# if VAR empty - run this
if [-z "${VAR}" ]; then
# some complex formula for VAR. Output is string.
VAR = 'blablabla'
fi
在example.sh文件中的下一次运行中的VAR varable被定义为'blablabla'。我怎么能这样做?
答案 0 :(得分:3)
我建议传入VAR
作为输入参数。
然后,您可以在其自身内递归调用脚本:
#!/bin/bash
VAR=$1
# if VAR empty - run this
if [ -z "${VAR}" ]; then
# some complex formula for VAR. Output is string.
VAR='blablabla'
$0 $VAR # recursively call script with new VAR
fi
exit 0
答案 1 :(得分:0)
我的版本:
#!/bin/bash
VAR=
FULL_PATH_TO_SCRIPT = $( readlink -m $( type -p $0 ))
# if VAR empty - run this
if [-z "${VAR}" ]; then
# some complex formula for VAR. Output is string.
VAR = blablabla
sed -i '0, /VAR=/s//VAR='${VAR}'/' $FULL_PATH_TO_SCRIPT
fi
exit 0
答案 2 :(得分:0)
不要修改脚本本身。将必要的VAR
值写入外部文件,并在脚本启动时从该文件中读取。
var_file=/var/lib/myscript/var # Just an example; put the file where convenient
read VAR < "$var_file"
# Compute value of VAR for next time
echo "$VAR" > "$var_file"