【发布时间】:2016-11-28 20:48:19
【问题描述】:
我正在尝试在 Ubuntu 中使用 BASH 创建报告,我想要的第一步是询问用户是否要附加到预先存在的文件,但是我无法让 > 或 >> 正常工作。有没有更好的方法来完成?
我希望变量方法只是为了了解我如何做到这一点。我知道我可以对它们进行硬编码,但我想稍后在代码中使用相同的变量,所以选择很重要
#!/bin/bash
DIR="/tmp/"
#REPORT="$HOSTNAME"_$(date +%Y%m%d%S)
REPORT="$HOSTNAME"_$(date +%Y%m%d)
if [ -f "$DIR""$REPORT" ]
then
PS3="Report exists append to record? [y][n]: "
options=("Yes" "No")
select yn in "${options[@]}";
do
case $REPLY in
"y" | "yes" | "Yes" | "YES" )
echo "You want to add to the file"
APPEND=">>"
echo "Ur cmd: echo \"Testing\" $APPEND $DIR$REPORT"
echo "Testing" $APPEND $DIR$REPORT
break
;;
"n" | "no" | "No" | "NO" )
echo "You want to delete the file"
APPEND='>'
echo "Ur cmd: echo \"Testing\" $APPEND $DIR$REPORT"
echo "Testing" $APPEND $DIR$REPORT
break
;;
* )
echo "Your choice was not understood"
;;
esac
done
else
echo "Creating $DIR$REPORT"
touch $DIR$REPORT
fi
【问题讨论】:
-
I/O 在变量之前被解释,因此您不能将运算符存储在变量中。
-
你可以使用
eval吗?它在某种程度上很强大,它可以在字符串形成时执行它们 -
不要将
eval用于这种微不足道的事情。这是一个等待发生的错误。 -
@chepner:在这种情况下,这是一个直接的用法!理想情况下,口译员无法知道的错误是什么?或者你所说的
bug waiting to happen是什么意思? -
@Inian
DIR="/tmp/foo;bar"
标签: bash variables ubuntu ubuntu-14.04